TSQL数据类型在减法运算符

时间:2017-10-27 11:41:05

标签: sql-server tsql while-loop

我正在使用while循环迭代一些表并在字段上执行替换,以删除所有连字符。所有字段都是varchar。

DECLARE @Table TABLE (TableName VARCHAR(max),Id int identity(1,1))
INSERT INTO @Table
Select distinct table_name From INFORMATION_SCHEMA.COLUMNS
DECLARE @max int
DECLARE @SQL VARCHAR(max) 
DECLARE @TableName VARCHAR(max)
DECLARE @id int = 1
select @max = MAX(Id) from @Table
WHILE (@id <= @max) 
BEGIN
    SELECT @TableName = TableName FROM @Table WHERE Id = @id
    SET @SQL = 'update '+ @TableName +' set colA = replace(colA,'-','');'
    EXEC(@SQL)
SET @id = @id +1
END

我收到的错误是:

  

数据类型varchar(max)和varchar在减法运算符中不兼容。

我尝试将varchar变量更改为固定长度或全部更改为max,但似乎没有任何效果。

1 个答案:

答案 0 :(得分:3)

在字符串中创建单引号时,您需要使用两个单引号:

DECLARE @Table TABLE (TableName VARCHAR(max),Id int identity(1,1))
INSERT INTO @Table
Select distinct table_name From INFORMATION_SCHEMA.COLUMNS
DECLARE @max int
DECLARE @SQL VARCHAR(max) 
DECLARE @TableName VARCHAR(max)
DECLARE @id int = 1
select @max = MAX(Id) from @Table
WHILE (@id <= @max) 
BEGIN
    SELECT @TableName = TableName FROM @Table WHERE Id = @id
    SET @SQL = 'update '+ @TableName +' set colA = replace(colA,''-'','''');'
    EXEC(@SQL)
SET @id = @id +1
END