1 DECLARE @table SYSNAME
2 SELECT @table = '替换为相应的表名'
3 DECLARE @insert_sql VARCHAR(MAX)
4 SELECT @insert_sql =
5 CASE
6 WHEN @insert_sql IS NULL
7 THEN '''INSERT INTO ' + @table + ' SELECT ''+'
8 ELSE @insert_sql + '+'',''+'
9 END
+ 'CASE WHEN ' + name + ' IS NULL THEN ''NULL'' ELSE ' +
CASE
WHEN RIGHT(TYPE_NAME(system_type_id),4) IN ('CHAR','TEXT')
THEN '''''''''+' + name + '+'''''''''
WHEN TYPE_NAME(system_type_id) IN ('DATETIME','UNIQUEIDENTIFIER')
THEN '''''''''+CAST(' + name + ' AS VARCHAR(100))+'''''''''
ELSE 'CAST(' + name + ' AS VARCHAR(100))'
END
+' END'
FROM sys.columns
WHERE object_id=OBJECT_ID(@table)
EXEC('SELECT ' + @insert_sql + ' FROM ' + @table )