SQL Server循环通过动态查询

时间:2018-05-10 08:40:42

标签: sql-server loops tsql dynamic-sql dynamicquery

我有一个程序,我将临时表名作为参数传递。对于里面的每个数据集,我需要获得rowcount。怎么做到这一点?

我需要类似的东西:

CREATE PROCEDURE sp_processing 
  @temp_table_name varchar(50)
AS
  DECLARE @log varchar(max)

/* get list of keys inside temp_table_name */
/* just a pseudo-code example */
SET @l_cursor = CURSOR FOR 
SELECT Key1, Key2, Key3, count(*) 
  FROM @temp_table_name -- table name passed as text 
 GROUP by Key1, Key2, Key3;

WHILE "there are results"
BEGIN
  @log += @Key1 +', '+ @Key2 +', '+ @Key3 +', '+ @count + CHAR(13)+CHAR(10);
END

UPDATE log_table SET log_column = @log WHERE....;

END /* procedure */

有没有办法循环呢?

我知道我可以选择将结果提取到table类型和THEN循环,但这需要使用表类型,所以想知道如果没有表变量这是否可以实现。

编辑:我只需要为每组密钥打印计数。

2 个答案:

答案 0 :(得分:1)

您应该始终尝试避免循环和光标。这是针对您的案例的基于集合的解决方案。请查看(特别是更新过滤器),看看它是否符合您的需求。

CREATE PROCEDURE sp_processing 
  @temp_table_name varchar(50)
AS
BEGIN

    DECLARE @DynamicSQL VARCHAR(MAX) = '

        ;WITH LogRecords AS
        (
            SELECT
                LogRecord = 
                    ISNULL(T.Key1, '''') + '','' + 
                    ISNULL(T.Key2, '''') + '','' +  
                    ISNULL(T.Key2, '''') + '','' + 
                    CONVERT(VARCHAR(20), COUNT(1))
            FROM
                QUOTENAME(''' + @temp_table_name + ''') AS T
            GROUP BY
                T.Key1,
                T.Key2,
                T.Key3
        )
        UPDATE L SET
            log_column = STUFF(
                (
                    SELECT
                        R.LogRecord + CHAR(13) + CHAR(10)
                    FROM
                        LogRecords AS R
                    FOR XML
                        PATH('')
                ),
                1, 1, '')
        FROM
            log_table AS L
        WHERE
            L.IdFilter = 999999999'

    PRINT @DynamicSQL

    -- EXEC (@DynamicSQL)

END

答案 1 :(得分:1)

这对我有用:

DECLARE @l_sql nvarchar(max)
DECLARE @temp_table_name varchar(50) = 'SOME_TABLE'
DECLARE @combinedString varchar(max)
SET @l_sql = 'SELECT @combinedString = COALESCE(@combinedString, '''') + convert(varchar,[Key1]) +'', ''+ convert(varchar,[Key3]) +'': ''+ convert(varchar,COUNT(*)) + ''| '' + CHAR(13)+CHAR(10) '
           + '  FROM ' + @temp_table_name  
           + ' GROUP BY [Key1], [Key3]'
           + ' ORDER BY [Key1], [Key3]';

EXECUTE sp_executesql @l_sql, N'@combinedString varchar(max) OUTPUT', @combinedString = @combinedString OUTPUT ;

SELECT @combinedString 

结果:

1, 1: 4| 
1, 2: 2| 
1, 3: 1| 
2, 5: 1|