SQL在游标内的列中计数

时间:2016-12-23 15:23:26

标签: sql-server tsql

想要做的是:

declare @Count numeric (10)
set @Count = 0
set @Count = (select count(*) from FILENAME where COLUMNNAME like '%e%')
print(@tel)

我希望在一些包含大量列并且所有列都有总数的文件上完成,所以我的想法是通过doint获取每个文件的列表:

select * from sys.columns 
where object_id = ( select object_id from sys.objects where name = 'FILENAME')

现在我认为最简单的方法是使用游标并将@Counts添加到另一个变量中。但我遇到的问题是,当COLUMNNAME位于游标中的变量时,我只能(据我所知)进行查询:

    declare @SQL varchar(max)
    set @SQL = @SQL + 'set @Count = (select count(*) from FILENAME where ' 
+ @columnname + ' like ''%e%'' )'

set @tot_Count = @tot_Count + @Count

但是据我所知,从光标内部读取动态sql是一个很大的问题。 虽然当我看到" print(sql)"这些查询似乎是正确的,似乎并没有在cursos中发挥作用。

有没有其他方法可以获得我想要的结果? 或者我在这里做错了什么?

作为参考,这是我的总体想法:

DECLARE @columnname VARCHAR(50) 
DECLARE @tot_Count NUMERIC(10), @Count NUMERIC(10)
set @tot_Count = 0

DECLARE MyCursor CURSOR FOR  
    SELECT name 
    from sys.columns 
        where object_id = ( select object_id from sys.objects where name = 'FILENAME' )

open MyCursor
FETCH NEXT FROM MyCursor INTO @columnname

WHILE @@FETCH_STATUS = 0
BEGIN
    declare @SQL varchar(max)
    set @SQL =''
    set @Count = 0
    set @SQL = @SQL + 'set @teller = (select count(*) from FILENAME where ' + @columnname + ' like ''%e%'' )'
    print (@SQL)
    exec (@SQL)

    set @tot_Count = @tot_Count + @Count

    FETCH NEXT FROM MyCursor into @name
END

CLOSE MyCursor
DEALLOCATE MyCursor 

print (@tot_teller)

2 个答案:

答案 0 :(得分:1)

DECLARE @tot_Count int = 0
DECLARE @Separator varchar(1) = ','
DECLARE @Position INT = 1 
DECLARE @ColumnNameList varchar(MAX)
DECLARE @ColumnName varchar(1000)
DECLARE @SQL varchar(max) = ''

SET @ColumnNameList = STUFF(( SELECT name 
    from sys.columns 
        where object_id in ( select object_id from sys.objects where name = 'FILENAME' )  FOR XML PATH('')),1,1,'')+',' 

--print @FileNameList

 WHILE (CHARINDEX(@Separator,@ColumnNameList,@Position)!=0)
 BEGIN
 SET @ColumnName = SUBSTRING(@ColumnNameList,@Position,CHARINDEX(@Separator,@ColumnNameList,@Position)-@Position) 
 SET @SQL = @SQL + 'set @tot_Count = (select count(*) from FILENAME where ' + @ColumnName + ' like ''%e%'' )'
   -- print (@SQL)
 EXEC (@SQL)
 SET @tot_Count = @tot_Count + @tot_Count
 SET @Position = CHARINDEX(@Separator,@ColumnNameList,@Position)+1
 END

 PRINT (@tot_Count)

答案 1 :(得分:1)

变体1:您可以使用动态变量代替光标操作。

document.getElementById("lbl1").childNodes[0].innerHTML;

它更短,更好,但是exec受到4000个字符的限制。

变体2:或者您可以使用光标并通过动态qry插入预先准备好的临时表。

declare @qry varchar(max)
select @qry = isnull(@qry + ' union all', '') + ' select count(*) cnt from ' + object_name(object_id) + ' where ' + name + ' like ''%e%'''
from sys.columns
where object_id = object_id('YourTableName')

set @qry = 'select sum(cnt) from (' + @qry + ') q'
print @qry
exec (@qry)