进行打印选择然后插入到(具有相同列定义的tbl)。以相同的顺序创建具有相同列的表。然后将插入插入到您的表中(您的列的顺序与 exec() 的输出顺序相同。将来表列的任何更改都可能会破坏这一点。表和查询应该具有相同的列。如果您谨慎并控制选择和插入中的列顺序,表列顺序无关紧要,但这仍然是恕我直言的好习惯。
示例(使用动态 sql 插入表中)
if object_id('dbo.ColumnMatch','U') is not null drop table dbo.ColumnMatch;
create table dbo.ColumnMatch (
id int identity(1,1) not null primary key
,column_name varchar(512)
);
declare @col varchar(256) = 'This Column Name'
declare @s varchar(max) = 'select ''' + @col + '''';
insert into ColumnMatch (column_name)
exec(@s);
select * from ColumnMatch;
不是打印,而是选择并修复 Insert Into 语句。:)
if object_id('dbo.ColumnMatch','U') is not null drop table dbo.ColumnMatch;
create table dbo.ColumnMatch (
id int identity(1,1) not null primary key
,column_name varchar(512)
);
declare @col varchar(255), @cmd varchar(max)
DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID =
c.Object_ID
WHERE t.Name = 'Account'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM Account WHERE [' + @col +
'] IS NOT NULL) BEGIN select ''' + @col + ''' column_name end'
Insert into ColumnMatch (column_name)
EXEC(@cmd)
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo
select * from ColumnMatch;