我有一个临时表#temp
,其中包含要插入永久表(名称为Customer
)的所有详细信息。
两个表的列名相同,但数据类型不同
(在#temp
表中,所有列的数据类型都是NVARCHAR
,但在customer
表中列可能包含BIT, Date, INT
ect')所以我需要在插入{{{ 1}}表。
这需要是一个动态过程,因为我不知道列名或数据类型。
答案 0 :(得分:1)
这应该让你开始:
DECLARE @TargetTableName sysname = 'Customer',
@SourceTableName sysname = '#temp'
-- start the dynamic sql
DECLARE @Sql nvarchar(max) = 'INSERT INTO '+ @TargetTableName +' ('
-- get the columns list
SELECT @Sql = @Sql + COLUMN_NAME +', '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TargetTableName
-- remove the last ', ' and add ') SELECT'
SET @Sql = LEFT(@Sql, LEN(@sql)-2) +') SELECT '
-- Select the column names and types to create
-- CAST(ColumnName As DataType[(Length)]) for each column
SELECT @Sql = @Sql + 'CAST('+ COLUMN_NAME +' As '+ DATA_TYPE +
CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN
'(max)'
WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL THEN
'('+ CAST(CHARACTER_MAXIMUM_LENGTH as varchar(10)) +')'
ELSE
''
END +'), '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TargetTableName
-- remove the last comma and add the FROM clause
SET @Sql = LEFT(@Sql, LEN(@sql)-1) + ' FROM '+ @SourceTableName
SELECT @Sql -- this, of course, should be EXEC @Sql, but I recommend leaving it as SELECT or PRINT until you get the exact sql you need.
注意:对于日期列,您应该考虑使用CONVERT而不是CAST,尤其是如果您知道#temp表中的日期格式。