如何在SQL Server中使用变量而不是列引用?

时间:2014-04-18 10:22:21

标签: sql sql-server variables select

我有以下存储过程。

如何使用变量(@selection)代替col1,esp。将此称为a.col1?

AS
BEGIN
    @selection nvarchar(100)

    SET NOCOUNT ON;

    SELECT col1, total_count,
      (SELECT COUNT(*)
       FROM LogTable
       WHERE Category LIKE '2014-04%' AND col1=a.col1 AND col2=col3
      ) AS match_count,
      (100*match_count/total_count) AS match_percentage
    FROM (
      SELECT col1, COUNT(*) AS total_count
      FROM LogTable
      WHERE Category LIKE '2014-04%'
      GROUP BY col1
    ) a
END

1 个答案:

答案 0 :(得分:1)

首先,您的查询在语法上甚至不正确(您无法在同一级别定义和使用match_count)。我认为以下是一个等效且更简单的查询:

      SELECT col1, COUNT(*) AS total_count,
             SUM(case when col2 = col3 then 1 else 0 end) as match_count
             100*AVG(case when col2 = col3 then 1.0 else 0.0 end) as match_percent
      FROM LogTable
      WHERE Category LIKE '2014-04%'
      GROUP BY col1;

这是动态SQL(或其良好的近似值):

BEGIN
    DECLARE @selection nvarchar(100);
    DECLARE @sql nvarchar(max);

    SET @sql = N'
SELECT <col1>, COUNT(*) AS total_count,
       SUM(case when col2 = col3 then 1 else 0 end) as match_count
       100*AVG(case when col2 = col3 then 1.0 else 0.0 end) as match_percent
FROM LogTable
WHERE Category LIKE '2014-04%'
GROUP BY <col1>';

    SET @sql = replace(@sql, '<col1>', @selection);

    EXEC sp_executesql @sql;
END;