T-SQL:如何将数据添加到存储在字符串中的列中?

时间:2016-05-18 08:06:58

标签: tsql

我想在t-sql中创建一个包含13列(YEAR ||个月)的变量表,并将列名存储到数组中。
然后使用循环我想在每列中输入数据。

例如:

for i 1..12 
insert into @tablename (@i)

有可能吗? 我需要创建游标吗?

1 个答案:

答案 0 :(得分:0)

我无法正确理解你的问题,这是你要找的吗?

下面的代码将循环三次并插入相应的列。

注意:您无法使用动态SQL实现表变量。您必须为此目的使用物理或临时表。

DECLARE @fmth varchar(32) = 'January.February.March'; 
DECLARE @smth varchar(32) = 'April.May.June'; 
DECLARE @tmth varchar(32) = 'July.August.September'; 
DECLARE @fomth varchar (32) = 'October.November.December'; 
DECLARE @mth varchar(10); 
DECLARE @i INT =3; 

CREATE TABLE #Report  
( Year smallint, January int, February int, March int, April int, May int, June int, July int, August int, 
September int, October int, November int, December int ) 

WHILE(@I > 0)
BEGIN
     DECLARE @IChar Varchar(5) = CAST(@I AS VArchar(5))
     DECLARE @Month1 varchar(20) =   PARSENAME(@fmth,@i) 
     DECLARE @Month2 varchar(20) =   PARSENAME(@smth,@i)
     DECLARE @Month3 varchar(20) =   PARSENAME(@tmth,@i)
     DECLARE @Month4 varchar(20) =   PARSENAME(@fomth,@i)

     -- Do Insert operation here 
        DECLARE @MyDynamicSQL VARCHAR(4000) 
        = 'INSERT INTO #Report('+@Month1+','+@Month2+','+@Month3+', '+@Month4+')
            VALUES ('+@IChar+','+@IChar+','+@IChar+','+@IChar+')'
            EXEC(@MyDynamicSQL) 

     SET @i = @I - 1
END
 SELECT * FROM #Report
DROP TABLE #Report