存储过程SQL中的Where子句

时间:2015-11-19 11:56:43

标签: sql-server stored-procedures

存储过程的新功能 - 有人可以帮我解决问题吗?我想实现一些简单的事情:

更新Table_A set Column_A = New Value其中Column_A = OldValue;

但将其转换为存储过程是有问题的。

alter PROC test_proc
@ColumnValue as Varchar(100),
@TableValue as Varchar(50),
@NewValue as Varchar(50),
@OldValue as Varchar(50)
as
begin

Declare @Pointer VarChar(1000)  

Declare Test_Cur Cursor For     
    Select 'Update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ''' + @NewValue + '''' 
    From INFORMATION_SCHEMA.COLUMNS 
    Where column_name = @OldValue
    and column_name = @ColumnValue
    and TABLE_NAME like @TableValue

Open Test_Cur  
-- Loop the cursor and execution of requests     
Fetch Next From Test_Cur Into @Pointer     
    While (@@Fetch_Status = 0)
    Begin  
      Print   @Pointer 
    Execute (@Pointer)     
    Fetch Next From Test_Cur Into @Pointer     
    End  

-- Closing the cursor and releasing resources     
    Close Test_Cur    
    Deallocate Test_Cur     
    Print 'Update complete!'

end

exec dbo.test_proc @ColumnValue = 'USERCHANGED',@TableValue = 'H_%',    @OldValue = '12', @NewValue = '14'

如果我删除“Where column_name = @OldValue”这一行,问题就出现了,但它无法帮助我实现目标。建议请。

2 个答案:

答案 0 :(得分:0)

这是光标的逻辑:

   Select 'Update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ''' + @NewValue + '''' 
    From INFORMATION_SCHEMA.COLUMNS 
    Where column_name = @OldValue and
----------^
          column_name = @ColumnValue and
----------^
          TABLE_NAME like @TableValue;

第一和第二个条件相互冲突。我认为你的意图只是:

   Select 'Update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ''' + @NewValue + '''' 
    From INFORMATION_SCHEMA.COLUMNS 
    Where column_name = @ColumnValue and
          TABLE_NAME like @TableValue;

您可能希望将@ColumnValue重命名为@ColumnName,这似乎更适合其使用。

编辑:

我认为你的意图是:

   Select 'Update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ''' + @NewValue + ''' where ' + COLUMN_NAME + ' = ''' + @NewValue + ''''
    From INFORMATION_SCHEMA.COLUMNS 
    Where column_name = @ColumnValue and
          TABLE_NAME like @TableValue;

答案 1 :(得分:0)

我认为你把内部与外部混合在一起,试试这个(我无法检查,可能是我错位了一个顶点):

alter PROC test_proc
@ColumnValue as Varchar(100),
@TableValue as Varchar(50),
@NewValue as Varchar(50),
@OldValue as Varchar(50)
as
begin

Declare @Pointer VarChar(1000)  

Declare Test_Cur Cursor For     
    Select 'Update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ''' + @NewValue + ''' WHERE ' +  + COLUMN_NAME + ' = ''' + @OldValue + ''''
    From INFORMATION_SCHEMA.COLUMNS 
    Where column_name = @ColumnValue
    and TABLE_NAME like @TableValue

Open Test_Cur  
-- Loop the cursor and execution of requests     
Fetch Next From Test_Cur Into @Pointer     
    While (@@Fetch_Status = 0)
    Begin  
      Print   @Pointer 
    Execute (@Pointer)     
    Fetch Next From Test_Cur Into @Pointer     
    End  

-- Closing the cursor and releasing resources     
    Close Test_Cur    
    Deallocate Test_Cur     
    Print 'Update complete!'

end