我需要在另一台服务器上使用2个表在服务器上创建一个表。
源服务器 下表1和表2的表定义相同 表1 ---- col 1,col2,col3 表2 ---- col4,col5,col6
目标服务器 表3 ---数据应该是表1和表2数据的结合
怎么做?感谢。
答案 0 :(得分:1)
所以我创建了一个名为EmptyDatabase
和Table1
,Table2
的测试数据库:
然后,根据您的需要,我创建了一个动态查询,该查询将生成此输出: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
表格已创建:
这也可以使用CURSOR
。