动态SQL - 从sql中的逗号分隔变量中选择表名

时间:2013-11-07 15:08:58

标签: sql tsql sql-server-2012

 DECLARE @tablename as varchar(MAX);
  SET  @tablename = '[dbo].[A_E_att_rate]
                    ,[Acute_total_cost]
                    ,[Average_los]
                    ,[D_days]
                    ,[days_1000]
                    ,[rate]';

    WHILE (SELECT * from [dbo].[fnSplitListToTable](@tablename)) > 0
    BEGIN
    EXEC(' SELECT t.[Commissionercode],
                t.[RiskBand Qadm],
                x.Col,
                x.Value
                FROM' + @tablename +' t
            CROSS APPLY 
            (
                VALUES
                    (''August'', t.[Sum of Aug12-Jul13]),
                    (''July'', t.[Sum of Jul12-Jun13]),
                    (''June'', t.[Sum of Jun12-May13]),
                    (''May'', t.[Sum of May12-Apr13]),
                    (''April'', t.[Sum of Apr12-Mar13])
            ) x (Col, Value)')

END

在上面的查询中,我试图从变量@tablename中获取表名。这是逗号分隔值。  我有兴趣在循环中使用每个表名。我该怎么做?

1 个答案:

答案 0 :(得分:0)

这就是我要做的。感谢您的反馈!

DECLARE @tablename as varchar(MAX), @d AS nvarchar(100), @SQL NVARCHAR(MAX);
  SET  @tablename = N'[dbo].[A_E_att_rate],[Acute_total_cost],[Average_los],[D_days],[days_1000],[rate]';
  SET @d = N',';
    SET @SQL = N'';
;WITH
t AS
(
    SELECT
       CAST(@tablename AS NVARCHAR(MAX)) AS tn,
       CAST(@tablename AS NVARCHAR(MAX)) AS r,
       CAST(0 AS INT) AS i
    UNION ALL
    SELECT
       CASE WHEN CHARINDEX(@d, r) <> 0 THEN
       CAST(
          STUFF(r, CHARINDEX(@d, r), LEN(r), N'')
          AS NVARCHAR(MAX))
          ELSE
          r
          END
          ,
       CASE WHEN CHARINDEX(@d, r) <> 0 THEN
       CAST(
          STUFF(r, 1, CHARINDEX(@d, r), N'')
          AS NVARCHAR(MAX))
          ELSE
          NULL
          END
          ,
       i + 1
    FROM
       t
    WHERE
       r IS NOT NULL
)
SELECT @SQL = N'SELECT t.[Commissionercode], t.[RiskBand Qadm], x.Col, x.Value FROM ' + tn + N' AS t CROSS APPLY 
            (
                VALUES
                    (''August'', t.[Sum of Aug12-Jul13]),
                    (''July'', t.[Sum of Jul12-Jun13]),
                    (''June'', t.[Sum of Jun12-May13]),
                    (''May'', t.[Sum of May12-Apr13]),
                    (''April'', t.[Sum of Apr12-Mar13])
            ) x (Col, Value)' FROM t WHERE i > 0

EXEC sp_executesql @SQL