查询不考虑where子句中的条件

时间:2016-12-22 14:40:59

标签: sql-server

我正在尝试执行下面的脚本一切正常但它没有考虑where子句(@inputfield is not null)中的条件。

请帮我解决这个问题

Declare @inputfield as varchar(100)
Declare @fields as cursor

create table #Temptable (inputfields varchar(200))
insert into #Temptable values ('streetAddress')
insert into #Temptable values ('zipcode')

set @fields= cursor for Select * from #temptable

Open @fields 
fetch next from @fields into @inputfield

While (@@FETCH_STATUS=0)

Begin
            insert into temptableoutput
            Select @inputfield ,count(Distinct objectId) as Entitiescount
            from temptable1
            where @inputfield is not null


Fetch next from @fields into @inputfield

End

Close @fields
deallocate @fields

谢谢, 苏尼

1 个答案:

答案 0 :(得分:0)

使用动态查询构建您的sql语句

Declare @inputfield as varchar(100)
Declare @fields as cursor
Declare @sql as nvarchar(500)

create table #Temptable (inputfields varchar(200))
insert into #Temptable values ('streetAddress')
insert into #Temptable values ('zipcode')

set @fields= cursor for Select * from #temptable

Open @fields 
fetch next from @fields into @inputfield

While (@@FETCH_STATUS=0)

Begin
            set @sql = 'insert into temptableoutput ' +
                        'Select ' + @inputfield + ' ,count(Distinct objectId) as Entitiescount ' +
                        'from temptable1 where ' + @inputfield + ' is not null'

            exec sp_executesql @sql

Fetch next from @fields into @inputfield

End

Close @fields
deallocate @fields