2016-01-21 117 views
1

在這個命名約定中我們有很多臨時表:temp_table_20153112。從這些表中,有一個名爲Manager的字段。我們想要識別那些表格Manager IS NULL。 這是我目前列出的所有以temp_table_開頭的表格,但我不知道如何重新查詢結果集。有任何想法嗎?搜索多個表的字段

SELECT t.name AS table_name, 
     c.name AS column_name 
FROM sys.tables AS t 
INNER JOIN sys.columns c ON t.object_id = c.object_id 
WHERE t.name LIKE '%temp_table_%' 
    AND c.name = 'Manager' 
+1

'經理是NULL' - 列或值在此列? – Devart

+0

@Devart值在這一列中。 – alwaysVBNET

+0

所以您的預期輸出只是其中列Manager中的值至少有一個值爲空的表的名稱? – ughai

回答

1
DECLARE @SQL NVARCHAR(MAX) 

SELECT @SQL = STUFF((
    SELECT ' 
UNION ALL 
SELECT TOP(1) ''' + name + ''' AS tbl FROM ' + name + ' WHERE Manager IS NULL' 
    FROM (
     SELECT name = QUOTENAME(SCHEMA_NAME(o.[schema_id])) + '.' + QUOTENAME(o.name) 
     FROM sys.objects o 
     JOIN sys.columns c ON o.[object_id] = c.[object_id] 
     WHERE o.name LIKE 'temp_table_%' 
      AND c.name = 'Manager' 
      AND c.is_nullable = 1 
    ) t 
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 13, '') 

--PRINT @SQL 
EXEC sys.sp_executesql @SQL 

輸出 -

SELECT TOP(1) '[dbo].[temp_table_2342]' AS tbl FROM [dbo].[temp_table_2342] WHERE Manager IS NULL 
UNION ALL 
SELECT TOP(1) '[dbo].[temp_table_234]' AS tbl FROM [dbo].[temp_table_234] WHERE Manager IS NULL 
UNION ALL 
... 
+0

你的回答是正確的,但作爲存儲過程執行。它可能不是一個sp或函數嗎? – alwaysVBNET

+0

如果不久 - 沒有。請提供更多關於您需要做什麼以及在哪裏的信息... – Devart

+0

基本上我希望它在頁面上提供網格,所以我從數據採集器獲取結果。我已經接受你的答案。如果太麻煩,不要擔心。很好的回答 – alwaysVBNET

1
DECLARE 
    @table_name SYSNAME, 
    @sql VARCHAR(2000) 
DECLARE tables CURSOR FOR 
    SELECT DISTINCT t.name AS table_name 
    FROM sys.tables AS t 
    INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
    WHERE t.name LIKE '%temp_table_%' 
     AND c.name = 'Manager' 
OPEN tables 
FETCH NEXT FROM tables INTO @table_name 
WHILE (@@FETCH_STATUS = 0) 
BEGIN 
    SET @sql = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [Manager] IS NULL) RAISERROR(''' + @table_name + ''',0,1) WITH NOWAIT' 
    EXECUTE(@sql) 
    FETCH NEXT FROM tables INTO @table_name 
END 
CLOSE tables 
DEALLOCATE tables 
+0

This works too。 – alwaysVBNET