我有一个游标,用于在数据库中查找NULL列。我正在使用它来消除使用dbAMP从将此数据上载到Salesforce的NULL列。我想对此进行修改,以将结果假脱机到表中,并包括表名和列名。
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 print ''' + @col + ''' end'
EXEC(@cmd)
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo
我在修改此游标以将结果放入表中还没有成功。任何指导将不胜感激。
答案 0 :(得分:1)
进行“打印”选择,然后插入到(具有相同列定义的tbl)。 用相同的顺序创建具有相同列的表。 然后将一个Insert插入yourtable(您的列,其顺序与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;
不打印,而是选择并修复“插入到”语句。 :)
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;