1
 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 中获取表名。这是一个逗号分隔的值。我有兴趣在循环中使用每个表名。我该怎么做呢 ?

4

1 回答 1

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
于 2013-11-07T20:47:37.057 回答