如何查询一条记录中所有为空的字段名:
ID   name   num   test1   test2 
1    null     22    null    null查询后显示为
name   test1   test2 
反正要得到所有为空的字段名称

解决方案 »

  1.   

    if object_id('tbTest') is not null
        drop table tbTest
    GO
    ----创建测试数据
    create table tbTest(ID int,name varchar(10),num int,test1 varchar(10),test2 varchar(10))
    insert tbTest
    select null,null,null,null,null union all
    select 1,    null,     22,    null,    null----创建SQL字符串
    declare @str varchar(8000)
    set @str = ''
    select @str = @str + ' and ' + name + ' is null' from syscolumns where id = object_id('tbTest')
    set @str = 'select * from tbTest where ' +  + stuff(@str,1,4,'')----查看SQL字符串
    print @str----执行SQL语句
    EXEC(@str)/*结果
    ID      name    num     test1   test2
    ------------------------------------------
    NULL    NULL    NULL    NULL    NULL
    */
      

  2.   

    所有为空的字段名称?只要为空就显示?
    select * from tb where id is null or name is null or num is null or test1 is null or test2 is null整行记录为空?
    select * from tb where id is null and name is null and num is null and test1 is null and test2 is null
      

  3.   

    多谢两位啊
    我的意思是得到一条记录的,
    而且得到的是字段名称,比如返回一个varchar(100) Columes
    Columes='name,num ,test1'   
    最后要看到的效果是 'name,num ,test1'
      

  4.   

    抱歉,一楼的回复看跑题了.这样试试:
    if object_id('tbTest') is not null
        drop table tbTest
    GO
    ----创建测试数据
    create table tbTest(ID int,name varchar(10),num int,test1 varchar(10),test2 varchar(10))
    insert tbTest
    select 1,    null,     22,    null,    null----创建SQL字符串
    declare @str varchar(8000)
    set @str = ''
    select @str = @str + ' union all select ''' + name + ''' from tbTest where ' + name + ' is null' 
    from syscolumns where id = object_id('tbTest')
    set @str = stuff(@str,1,10,'')----查看SQL字符串
    print @str----执行SQL语句
    EXEC(@str)/*结果
    name
    test1
    test2
    */
      

  5.   

    to hellowork(一两清风) ( 
    非常感谢
    如果换成其他表有条件的怎么换?
    比如where id=1
      

  6.   

    把条件加到'where ' + 列名 + 'is null'后面就行了,类似:
    'where ' + 列名 + 'is null AND 其它条件'.例如:
    if object_id('tbTest') is not null
        drop table tbTest
    GO
    ----创建测试数据
    create table tbTest(ID int,name varchar(10),num int,test1 varchar(10),test2 varchar(10))
    insert tbTest
    select 1,    null,     22,    null,    null----创建SQL字符串
    declare @str varchar(8000)
    set @str = ''
    select @str = @str + ' union all select ''' + name + ''' from tbTest where ' + name + ' is null and id = 1'   /*在此添加其它条件*/
    from syscolumns where id = object_id('tbTest')
    set @str = stuff(@str,1,10,'')----查看SQL字符串
    print @str----执行SQL语句
    EXEC(@str)/*结果
    name
    test1
    test2
    */
      

  7.   

    to hellowork(一两清风) ,楼主的意思好象是要这样的结果:name,test1,test2
    那么应该怎么改呢?
      

  8.   

    非常感谢大家,准备接贴了
    特别感谢hellowork(一两清风)