SQL动态列名称作为计数器

时间:2019-01-14 21:15:36

标签: sql sql-server dynamic

我正在使用Microsoft SQL Server,我想编写一个动态SQL查询,该查询将通过检查WHERE子句中的不同列来更新行。

WHERE子句中的列的格式为X1,X2,...,X10-因此我想在每次迭代时使用@cnt作为与列名X串联的计数器。

我不断收到错误消息:

  

数据库“ DBName”的事务日志为   由于“ LOG_BACKUP”已满

如果我写10次查询,它就可以正常工作,因此应该与循环有关,或者将int转换为char

到目前为止,这是我的查询-添加了所有重要部分:

 @y char(3) //SP Parameter

 DECLARE @table varchar(50)
 DECLARE @sql varchar(max)

 DECLARE @cnt INT = 1
 DECLARE @count VARCHAR(2)

 SET @table = CONCAT('X_',@y)

 WHILE @cnt <= 10     
   SET @count = CAST(@cnt as VARCHAR);
BEGIN
  SET @sql = CONCAT('UPDATE ',@table,' SET X1 = CASE WHEN X1 <> '''' THEN X1 ELSE ''VALUE'' END,
  X2 = CASE WHEN X1 = '''' or X2 <> '''' THEN X2 ELSE ''VALUE'' END,
  X3 = CASE WHEN X2 = '''' or X3 <> '''' THEN X3 ELSE ''VALUE'' END,
  X4 = CASE WHEN X3 = '''' or X4 <> '''' THEN X4 ELSE ''VALUE'' END,
  X5 = CASE WHEN X4 = '''' or X5 <> '''' THEN X5 ELSE ''VALUE'' END,
  X6 = CASE WHEN X5 = '''' or X6 <> '''' THEN X6 ELSE ''VALUE'' END,
  X7 = CASE WHEN X6 = '''' or X7 <> '''' THEN X7 ELSE ''VALUE'' END,
  X8 = CASE WHEN X7 = '''' or X8 <> '''' THEN X8 ELSE ''VALUE'' END,
  X9 = CASE WHEN X8 = '''' or X9 <> '''' THEN X9 ELSE ''VALUE'' END,
  X10 = CASE WHEN X9 = '''' or X10 <> '''' THEN X10 ELSE ''VALUE'' END
  WHERE X'+@count+' IN (SELECT P_CODE FROM P WHERE DESCRIPTION LIKE ''%new%'' AND Y= ''',@y,''');
  EXEC (@sql);
  SET @cnt=@cnt+1;
 END

1 个答案:

答案 0 :(得分:0)

我只是试图纠正语法,不知道最终目标是什么?

declare @y char(3)='1'

DECLARE @table varchar(50)

DECLARE @sql varchar(max)

DECLARE @cnt INT = 1

DECLARE @count VARCHAR(30)

SET @table = CONCAT('X_',@y)

WHILE (@cnt <= 10 )

BEGIN

SET @count = CAST(@cnt as VARCHAR(3));


set @sql=''


SET @sql = 'UPDATE '+@table+' SET X1 = CASE WHEN X1 <> '''' THEN X1 ELSE ''VALUE'' END,
X2 = CASE WHEN X1 = '''' or X2 <> '''' THEN X2 ELSE ''VALUE'' END,
X3 = CASE WHEN X2 = '''' or X3 <> '''' THEN X3 ELSE ''VALUE'' END,
X4 = CASE WHEN X3 = '''' or X4 <> '''' THEN X4 ELSE ''VALUE'' END,
X5 = CASE WHEN X4 = '''' or X5 <> '''' THEN X5 ELSE ''VALUE'' END,
X6 = CASE WHEN X5 = '''' or X6 <> '''' THEN X6 ELSE ''VALUE'' END,
X7 = CASE WHEN X6 = '''' or X7 <> '''' THEN X7 ELSE ''VALUE'' END,
X8 = CASE WHEN X7 = '''' or X8 <> '''' THEN X8 ELSE ''VALUE'' END,
X9 = CASE WHEN X8 = '''' or X9 <> '''' THEN X9 ELSE ''VALUE'' END,
X10 = CASE WHEN X9 = '''' or X10 <> '''' THEN X10 ELSE ''VALUE'' END
WHERE X'+@count+' IN (SELECT P_CODE FROM P WHERE [DESCRIPTION] LIKE ''%new%'' AND Y= '+@y+')';
--EXEC (@sql);

print @sql

SET @cnt=@cnt+1;

END

I)避免使用RBAR(例如循环,光标)

ii)使用sp_executesql