2017-09-12 7 views
1

特定のテーブルに特定の列名があるかどうかをチェックしたい場合は、それらがすべてある場合はtrueを返し、1つの列名が存在しない場合はfalseを返すようにしたいと思います。SQLの行のセットが特定の値に収まるかどうかを確認しますか?

SELECT COLUMN_NAME 
FROM db.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'MyTable' 

は、私が確認したい場合は、クエリの結果では、これらの名前: ( 'UpdatedDate'、 'C​​reatedDateに'、 'UpdatedBy')あなたがリストでこのクエリのヘルプを数える知っていれば

答えて

0

あなた

SELECT COUNT(COLUMN_NAME) 
FROM db.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'MyTable' AND COLUMN_NAME IN ('UpdatedDate', 'CreatedDate', 'UpdatedBy') 
GROUP BY COLUMN_NAME HAVING COUNT(COLUMN_NAME) = 3; 
0

information_schema.columnsでチェックする必要がある列名を持つテーブル変数を作成します。次に、テーブル変数とinformation_schema.columnsの間のチェックを行います。これがどれほど効率的かはわかりません。

クエリ

declare @cols as varchar(max) = 'UpdatedDate,CreatedDate,UpdatedBy'; 
declare @cols2 as varchar(max) = '(' + char(39); 

set @cols2 += replace(@cols, ',', '''),(''') + ''');'; 

declare @sql as varchar(max) = 'declare @tbl as table([col] varchar(1000));'; 
set @sql += 'insert into @tbl values' + @cols2; 
set @sql += 'declare @tot as int;set @tot = (select count(*) from @tbl);'; 
set @sql += 'select case when count(*) = @tot 
      then ''true'' else ''false'' end as [status] 
      from @tbl t1 where exists(
       select 1 from information_schema.columns t2 
       where t1.[col] = t2.[column_name] 
       and t2.[table_name] = ''MyTable'');'; 

exec(@sql); 
関連する問題