我正在运行以下代码,以从具有特定列的所有表中提取所有相关行。外IF
应该检查表中是否存在该迭代的列。如果没有,它应该完成该迭代并移动到下一个表。如果该表具有GCRecord
列,则应检查该表是否将返回任何记录。如果没有要返回的记录,它应该结束该迭代并继续下一个表。如果有记录,它应该在SSMS中显示。
USE WS_Live
EXECUTE sp_MSforeachtable
'
USE WS_Live
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCRecord''
)
BEGIN
IF EXISTS (SELECT * FROM ? WHERE GCRecord IS NOT NULL)
BEGIN
SELECT * FROM ? WHERE GCRecord IS NOT NULL
END
END
'
它似乎有效,因为SSMS只返回带有效条目的网格。我不明白的是:为什么我仍然会收到这些错误?
Msg 207, Level 16, State 1, Line 10
Invalid column name 'GCRecord'.
Msg 207, Level 16, State 1, Line 13
Invalid column name 'GCRecord'.
修改
使用建议后,我有:
USE WS_Live
EXECUTE sp_MSforeachtable
'
USE WS_Live
IF EXISTS(SELECT * FROM sys.columns WHERE columns.Object_ID = Object_ID(''?'')AND Name = ''GCRecord'')
BEGIN
IF EXISTS (SELECT * FROM ? WHERE GCRecord IS NOT NULL)
BEGIN
EXEC('' SELECT * FROM ? WHERE GCRecord IS NOT NULL'')
END
END
'
返回此错误:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'GCRecord'.
这是指这一行
IF EXISTS(SELECT * FROM sys.columns WHERE columns.Object_ID = Object_ID(''?'')AND Name = ''GCRecord'')
更新
我尝试嵌套EXEC
语句,这些语句不起作用,但是使用选定的答案我得到了我正在寻找没有错误的结果。
答案 0 :(得分:2)
在开始使用动态查询以避免内部预编译代码,因为表格不包含列“GCRecord
”
USE WS_Live
GO
EXECUTE sp_MSforeachtable
'
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCRecord''
)
BEGIN
EXEC(''
IF EXISTS (SELECT * FROM ? WHERE GCRecord IS NOT NULL)
BEGIN
SELECT * FROM ? WHERE GCRecord IS NOT NULL
END
'')
END
'
答案 1 :(得分:2)
你非常接近。使用“EXEC”
USE WS_Live
EXECUTE sp_MSforeachtable
'
USE WS_Live
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCRecord''
)
BEGIN
EXEC(''SELECT * FROM ? WHERE GCRecord IS NOT NULL'')
END
'
答案 2 :(得分:0)
请尝试这个动态的SQL。准备好运行时从exec
删除评论
declare @t varchar(max) = ''
SELECT @t = @t + 'SELECT * FROM ' + a.name + ' WHERE GCRecord IS NOT NULL;' + char(13)
FROM sys.columns b join sys.objects a on
b.Object_ID = a.Object_ID
WHERE b.Name ='CreateDt'
Print @t
--exec (@t)
答案 3 :(得分:0)
使用@whereand简化:
exec sp_MSforeachtable
@command1='select * from ? where GCRecord is not null',
@whereand='and exists(select 1 from sys.columns c where c.object_id = o.id
and c.name = ''GCRecord'')'