如何检查select变量是否具有列值

时间:2017-11-28 07:55:31

标签: sql sql-server sql-server-2012

我有一个select语句,我将select语句分配给变量@ var1 现在我必须检查列是否有值使用@ var1是否可能?

SET @STRVAR1='SELECT  type, a.groupnumber, idnumber, relation,a.code,  flag, planname, a.insurancename, address1, address2, REPLACE(zipcode,-,'') AS zipcode, cityName, statecode,c.PrintBillProTaxonomy  FROM  TABLE1, TABLE2, TABLE3  WHERE  b.citycode=c.citycode and a.insurancecode = c.insurancecode  AND  Code = ''PT0000'' AND  a.No =  ''GT56789'' AND  a.Flag = ''SAMPLE''' 
    EXEC (@STRVAR1)

我的条件应该是:

IF @STRVAR.COLUMNNAME<>''
BEGIN
PRINT'TEXT'
END

1 个答案:

答案 0 :(得分:1)

您可以将查询结果保存在临时表或表变量中,然后查询该表:

使用表变量的示例:

declare @t1 table (type varchar(10), groupnumber int, idnumber int, etc....) 
-- you need to declare all your resultset columns here and their respective types 

declare @strvar1 nvarchar(max)
SET @strvar1='SELECT type, a.groupnumber, idnumber, relation,a.code,  flag, planname, a.insurancename, address1, address2, REPLACE(zipcode,-,'') AS zipcode, cityName, statecode,c.PrintBillProTaxonomy  
              FROM  TABLE1, TABLE2, TABLE3  
              WHERE  b.citycode=c.citycode and a.insurancecode = c.insurancecode  AND  Code = ''PT0000'' AND a.No =  ''GT56789'' AND a.Flag = ''SAMPLE''' 

insert into @t1
exec(@strvar1)

select * 
from @t1
where columnname <> ''

最好将查询的连接逻辑更改为modern proper join syntax