您可以通过查询数据字典在运行时动态构建 SQL 语句,如下所示:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Your_Table'
您可以使用它来动态构建 SQL 语句来执行此插入操作,并且其中包含所有列。
您可以在过程中执行上述操作T-SQL
,并且可以使用它sp_executesql
来运行动态构建的查询。例如,如果您的查询位于名为 的变量中@SQL
,您可以执行以下操作:
EXECUTE sp_executesql @SQL
下面给出了一个示例:
create table three (id int identity, other int)
create table four (id int identity, other int)
insert into three select 1
insert into three select 2
declare @sql nvarchar(max)
set @sql = REPLACE(
'
set identity_insert four on
insert into four (:columns:) select :columns: from three
set identity_insert four off',
':columns:',
stuff((
select ','+quotename(name)
from sys.columns
where object_id=object_id('four')-- and is_identity=0
for xml path('')),1,1,''))
EXECUTE sp_executesql @SQL