在表中为每个数据库查找具有空值的列

时间:2018-02-28 12:38:18

标签: sql sql-server sql-server-2008-r2

我的表包含Databasename,tablename,columnname,query等列。但在查询列SELECT COUNT(MachineName) AS Cnt FROM Keys WHERE MachineName<>NULL中 如何在表中使用此查询列执行(我需要执行查询列的剩余3列)可以任何人帮助我。

3 个答案:

答案 0 :(得分:1)

哦,我误会了。您是否正在搜索在查询列中执行查询的查询,并使用数据库中的值替换其中的某些值,如下例所示:

if object_ID('tempdb..Test') is null
begin
    create table tempdb..Test (
    dbname nvarchar(512),
    tblname nvarchar(512),
    columnename nvarchar(512),
    query nvarchar(MAX)
    )


    --  delete from tempdb..Test
    insert into tempdb..Test (dbname, tblname, columnename, query)
    values ('master','sysobjects','id','select count([col]) from [db]..[tbl] where [col] is not null') 

    insert into tempdb..Test (dbname, tblname, columnename, query)
    values ('master','syscolumns','id','select count([col]) from [db]..[tbl] where [col] is not null') 
end


declare @db nvarchar(512)
declare @tbl nvarchar(512)
declare @col nvarchar(512)
declare @qry nvarchar(512)
declare @cmd nvarchar(512)

declare cur_test cursor 
    for select dbname, tblname, columnename, query
    from tempdb..Test
open cur_test

FETCH NEXT FROM cur_test   
INTO @db, @tbl, @col, @qry

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @cmd = replace(replace(replace(@qry,'[db]', quotename(@db)), '[tbl]', quotename(@tbl)),'[col]', @col)
    exec sp_executesql @cmd


    FETCH NEXT FROM cur_test   
    INTO @db, @tbl, @col, @qry
END

close cur_test
deallocate cur_test  

答案 1 :(得分:0)

使用&#34; is&#34;与null进行比较。或&#34;不是&#34;操作

SELECT COUNT(MachineName) AS Cnt FROM Keys WHERE MachineName is not NULL

或者如果您想要列MachineName具有值的条目,请使用

SELECT COUNT(MachineName) AS Cnt FROM Keys WHERE MachineName is NULL

答案 2 :(得分:0)

您搜索的内容如下:

select 'select count(*) from ' + QUOTENAME(so.name) + ' where ' + (SELECT QUOTENAME(Name) + ' is null and ' 
           FROM syscolumns sc
           where sc.id= so.id
            FOR XML PATH('') ) + '1=1' 
from sysobjects so 
where so.xtype='U'
order by so.id