Итак, я создал тестовую базу данных с именами EmptyDatabase
и Table1
, Table2
, а также:
![enter image description here](https://i.stack.imgur.com/BsXHo.jpg)
Затем, согласно вашемунеобходимо, я создал динамический запрос, который будет выдавать этот вывод: CREATE TABLE dbo.Table3 (col1 varchar(50),col2 int,col3 decimal,col4 varchar(50),col5 int,col6 decimal)
и будет выполняться с sp_executesql
:
USE [EmptyDatabase]
-- Declare a temp table to store column names from Table 1 and 2.
DECLARE @TableColumns TABLE
(
RowNumber int IDENTITY(1,1),
TableName varchar(50),
ColumnName varchar(50),
DataType varchar(50),
Lenght integer
)
-- Query 'Table1' column names and insert them into the @TableColumns table.
INSERT INTO @TableColumns
SELECT
'Table1' AS TableName,
COLUMN_NAME,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH
FROM
[EmptyDatabase].INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = N'Table1'
-- Query 'Table2' column names and insert them into the @TableColumns table.
INSERT INTO @TableColumns
SELECT
'Table2' AS TableName,
COLUMN_NAME,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH
FROM
[EmptyDatabase].INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = N'Table2'
-- Count total rows.
DECLARE @id int
DECLARE @totalrows int = (SELECT COUNT(*) FROM @TableColumns)
DECLARE @currentrow int = 1
-- Declare variables to query the row's data.
DECLARE @columnName varchar(50)
DECLARE @dataType varchar(50)
DECLARE @lenght int
-- Declare the custom string to construct your dynamic query.
DECLARE @query nvarchar(MAX)
-- Start creating your dinamic query.
SET @query = 'CREATE TABLE dbo.Table3 ('
-- Iterate through the results.
WHILE @currentrow <= @totalrows
BEGIN
-- Get the current row's data.
SET @columnName = (SELECT ColumnName FROM @TableColumns WHERE RowNumber = @currentrow)
SET @dataType = (SELECT DataType FROM @TableColumns WHERE RowNumber = @currentrow)
SET @lenght = (SELECT Lenght FROM @TableColumns WHERE RowNumber = @currentrow)
-- Add column declaration.
SET @query += @columnName + ' ' + @dataType
-- If its a char type add its lenght.
IF @dataType = 'varchar'
BEGIN
SET @query += '(' + CAST(@lenght AS VARCHAR) + ')'
END
-- Add a comma after column declaration except to the last one.
IF @currentrow < @totalrows
BEGIN
SET @query += ','
END
-- Next row.
SET @currentrow += 1
END
-- Terminate the dynamic query string.
SET @query += ')'
-- Execute the dynamic query to create the table.
EXEC sp_executesql @query
И таблица будет создана:
![enter image description here](https://i.stack.imgur.com/tgHUe.jpg)
Это также можно сделать с помощью CURSOR
.