我有一个动态SQL语句,它生成一系列更新语句,但它不会将值包含在单引号中的set子句和where子句中。有谁知道如何解决这个问题?这是我的代码。
Declare @OldSSN VARCHAR(9)
Declare @NewSSN VARCHAR(9)
Declare @cmd VARCHAR(MAX)
Set @OldSSN='000000000'
Set @NewSSN='000000001'
Select @cmd = COALESCE(@cmd,'') +
'
UPDATE ' + TABLE_NAME + ' SET ' + Column_Name + ' = ' + @NewSSN + '
WHERE ' + Column_Name + ' = ' + @OldSSN +'
'
From INFORMATION_SCHEMA.COLUMNS
Where Column_Name like 'SSN%'
OR Column_Name LIKE 'ssn%'
OR Column_Name LIKE 'ssn%'
OR Column_Name LIKE '%_ssn%'
OR Column_Name LIKE '_ocsecno'
OR Column_Name LIKE 'Ssn%';
Select @cmd
执行时的输出
UPDATE appl_view
SET ssn = 000000001
WHERE ssn = 000000000
UPDATE ap_paid
SET ssn = 000000001
WHERE ssn = 000000000
我试图找出如何将ssn值括在单引号中,如下所示
UPDATE appl_view
SET ssn = '000000001'
WHERE ssn = '000000000'
UPDATE ap_paid
SET ssn = '000000001'
WHERE ssn = '000000000'
答案 0 :(得分:0)
使用三重单引号将引号转换为字符串
选择@cmd = COALESCE(@ cmd,'')+
'
更新' + TABLE_NAME +' SET' + Column_Name +' =''' + @NewSSN +''''
在哪里' + Column_Name +' =''' + @OldSSN +'''
'
答案 1 :(得分:0)
我假设你要在某个时候执行这个动态的sql?如果是这样,您可以使用sp_executesql
的参数功能,而不必担心引用。 (但是,您必须使用nvarchar
)。
这是一个简单的例子。
---------------------------------------------------------------------------
-- Create a table to test against
---------------------------------------------------------------------------
CREATE TABLE TestTable
(
TestTableID INT IDENTITY,
Text1 VARCHAR(10)
);
---------------------------------------------------------------------------
-- Seed the table
---------------------------------------------------------------------------
INSERT INTO TestTable
VALUES ( '000000000');
INSERT INTO TestTable
VALUES ( '000000003');
INSERT INTO TestTable
VALUES ( '000000004');
---------------------------------------------------------------------------
-- Make and execute dynamic sql
---------------------------------------------------------------------------
DECLARE @cmd NVARCHAR(100),
@SqlParms NVARCHAR(100);
SET @cmd = N'UPDATE TestTable SET Text1 = @NewSSN WHERE Text1 = @OldSSN';
SET @SqlParms = N'@NewSSN varchar(9), @OldSSN varchar(9)';
EXECUTE sp_executesql @cmd, @SqlParms, @NewSSN = N'000000001', @OldSSN = N'000000000';
---------------------------------------------------------------------------
-- Result should have updated the first row from '000000000' to '000000001'
---------------------------------------------------------------------------
SELECT * FROM TestTable;
答案 2 :(得分:-1)
Select @cmd = COALESCE(@cmd,'') +
'
UPDATE [' + TABLE_NAME + '] SET [' + Column_Name + '] = ''' + @NewSSN + '''
WHERE [' + Column_Name + '] = ''' + @OldSSN + '''
'