我想在表中找到ANY列满足特定条件的行。
例如,如果我有一个表RobTest
:
-- Example Table
create table #RobTest
(A varchar(10), B varchar(10), C varchar(10))
insert into #RobTest
select 'Blue', 'Green', 'Green' UNION ALL
select 'Green', 'Blue', 'Green' UNION ALL
select 'Green', 'Green', 'Green'
如果我想查找任何列中包含值为'Blue'
的字段的所有行,我可以写:
select * from #RobTest
where A = 'Blue' or B = 'Blue' or C = 'Blue'
并获取第1行和第2行。但是,如果表具有数十个列名,或者如果您无法确定列名可能会更改并且您将查询作为审计运行,则此解决方案可能会失败。那么如何动态地做到这一点?
答案 0 :(得分:0)
我们可以使用INFORMATION_SCHEMA.COLUMNS
查找列名,然后使用游标迭代所有列,使用动态SQL填充满足条件的行的临时表。
按照上面的代码,假设问题中给出了#RobTest
定义:
-- Find all columns of #RobTest
select COLUMN_NAME
INTO #ColumnNames
from tempdb.INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME like '%RobTest%'
-- Create a place to hold our results
select * into #RobTemp from #RobTest
truncate table #RobTemp
-- Set up varaibles for our iteration process
DECLARE @sql nvarchar(1000)
DECLARE @columnCursor CURSOR
DECLARE @currentColumn NVARCHAR(100)
SET @columnCursor = CURSOR FOR
SELECT COLUMN_NAME FROM #ColumnNames
-- Go through the columns one at a time and then run the query on that column.
OPEN @columnCursor
FETCH NEXT FROM @columnCursor INTO @currentColumn
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql = 'select * from #RobTest where ' + @currentColumn + ' = ''Blue'''
insert into #RobTemp
exec sp_executesql @sql
FETCH NEXT FROM @columnCursor INTO @currentColumn
END
-- Show the results
select * from #RobTemp