我的问题是如何在 select 语句中使用变量作为列名。我创建了变量@B 作为列名,即 BGNDATE1 到 BGNDATE12。我创建了一个 while 循环,而不是 12 个选择语句。列名基本上是 BGNDATE + 递增的整数。
我得到的错误是:
将 varchar 值“BGNDATE1”转换为数据类型 int 时转换失败。
USE X --this is the database
DECLARE @DATES TABLE (ROWID INT, FISCDATES INT)
DECLARE @FY INT = 2012
DECLARE @I INT
DECLARE @IV VARCHAR(2)
DECLARE @B VARCHAR(9)
SELECT @FY AS FY
SET @I = 1
WHILE @I <= 12
BEGIN
SET @IV = @I
SET @B = 'BGNDATE' + @IV
INSERT INTO @DATES (ROWID)
SELECT @I
MERGE INTO @DATES AS T
USING (
--这就是变量@B的错误所在
SELECT @B AS FISCDATES FROM DBO.Y -- Y is the table in the database
WHERE FSCYEAR = @FY) AS S
ON T.ROWID = @I
WHEN MATCHED
THEN UPDATE
SET T.FISCDATES = S.FISCDATES;
SET @I = @I + 1
END
SELECT * FROM @DATES