请帮我修复这个存储过程

时间:2015-04-08 20:06:30

标签: sql-server tsql stored-procedures dynamic-sql

当我尝试创建以下存储过程时,我收到以下错误消息: 我究竟做错了什么?

Create  Procedure uspUpdateWithNewSSN
    (
      @OldSSN VARCHAR(9)
      ,@NewSSN VARCHAR(9)
     )
       AS 
 SET NOCOUNT ON
 BEGIN
If OBJECT_ID(N'NewSSNEXIST') IS NULL
   Begin
    Create Table NewSSNEXIST
    (
       NewSSN nvarchar(9)NOT NULL   
    )
  End

 Begin
    Insert into  NewSSNEXIST
    Exec uspCheckNewSSN @NewSSN
    GO
 End

If (select count(*) from NewSSNEXIST)>0
Begin 
    print 'social security number already used'
    Truncate Table NewSSNEXIST;
    Return
End
Else
 --Begin update ssn 
Begin
--Declare @OldSSN VARCHAR(9)
--Declare @NewSSN VARCHAR(9)
Declare @cmd   VARCHAR(MAX)
--Set @OldSSN='222334444'
--Set @NewSSN='222334644'

 Select @cmd =  COALESCE(@cmd,'') +
'
    UPDATE [' + TABLE_SCHEMA + '].[' + 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
EXEC(@cmd)
End
    END

      GO

1 个答案:

答案 0 :(得分:0)

除了程序中的GO关键字,您还应该查看动态sql并按如下方式修复

Declare @cmd   VARCHAR(MAX)

 Select @cmd = N' UPDATE ' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) 
            +  N' SET  ' + QUOTENAME(c.name)   + N' =  @NewSSN   '
            +  N' WHERE ' + QUOTENAME(c.name)  + N' =  @OldSSN  '

From sys.tables t 
Inner join sys.columns c ON t.object_id = c.object_id
Inner join sys.schemas s on t.schema_id = s.schema_id
Where c.name like 'SSN%'       
OR c.name LIKE 'ssn%'          
OR c.name LIKE 'ssn%'          
OR c.name LIKE '%_ssn%'            
OR c.name LIKE '_ocsecno'          
OR c.name LIKE 'Ssn%';

--Select @cmd
EXEC sp_executesql @cmd
                  ,N' @OldSSN VARCHAR(9) ,@NewSSN VARCHAR(9)'
                  ,@OldSSN
                  ,@NewSSN