存储过程按参数更新特定列

时间:2016-05-09 03:05:07

标签: sql tsql

我正在开发一个存储过程来使用参数更新特定的列。

例如:

CREATE PROCEDURE save_proc
(
   @userid varchar(5),
   @column varchar(10),
   @data varchar(50)
)
AS
BEGIN
    UPDATE MyProfile 
    SET @column = @data 
    WHERE userid = @userid

以下是我尝试但无法正常工作的代码。是否可以通过参数更新特定列来进行此类更新?感谢

3 个答案:

答案 0 :(得分:1)

您可以在存储过程中构建查询并执行。

CREATE PROCEDURE save_proc
(
   @userid varchar(5),
   @column varchar(10),
   @data varchar(50)
)
AS
BEGIN
    exec sp_executesql N'UPDATE MyProfile SET ' + @column + '=''' + @data + ''' WHERE userid = ''' + @userid + ''''
END

然而,该方法可能会引起安全问题。

答案 1 :(得分:1)

它可行,但我会避免这样做....你的代码应该如下:

DECLARE @column varchar(10)
DECLARE @data varchar(50)
UPDATE DummyTable 
SET 
col1 = CASE WHEN @column = 'Col1' THEN @data ELSE col1 END ,
col2 = CASE WHEN @column = 'Col2' THEN @data ELSE col2 END
where userid =  @userid
.
.
.

希望这就是你要找的东西

答案 2 :(得分:0)

使用CASE语句会导致所有标识的列再次被更新;这将为列上的某些索引调用重新索引,其中即使发生相同的值,该更改也会发生。浪费服务器上的执行更新。

对于单个值,IF语句是最佳选择,尤其是在value与列数据类型不同的情况下。

IF(@fieldName IS NULL) SELECT @fieldName = ''
IF(@updateValue IS NULL) SELECT @updateValue = ''

DECLARE @myCount int
SELECT @myCount = count(*) FROM [dbo].[myTable] WHERE @inventoryID =  @updateInventoryID

--if no valid data to update,  return -1 for noUpdate
IF(0 = @updateInventoryID 
   OR 0 = @myCount 
   OR '' = @fieldName 
   OR '' = @updateValue)
RETURN -1


BEGIN TRAN

 IF('notes' = @fieldName)  
    UPDATE [dbo].[myTable] 
    SET [notes] = @updateValue, [modifyDate] = GETDATE() 
    WHERE [inventoryID] = @updateInventoryID


 IF('reorderPoint' = @fieldName)  
 BEGIN  
   SET @newValueInt = CONVERT(int, @updateValue)
   UPDATE [dbo].[myTable] 
    SET [reorderPoint] = @newValueInt, [modifyDate] = GETDATE() 
    WHERE [inventoryID] = @updateInventoryID
 END  


 IF('safetyStock' = @fieldName)  
 BEGIN  
   SET @newValueInt = CONVERT(int, @updateValue)
   UPDATE [dbo].[myTable] 
    SET [safetyStock] = @newValueInt, [modifyDate] = GETDATE() 
    WHERE [inventoryID] = @updateInventoryID
 END  


 IF('quantityOnHand' = @fieldName)  
 BEGIN  
   SET @newValueInt = CONVERT(int, @updateValue)
   UPDATE [dbo].[myTable] 
    SET [quantityOnHand] = @newValueInt, [modifyDate] = GETDATE() 
    WHERE [inventoryID] = @updateInventoryID
 END


 IF('totalLeadTimeDays' = @fieldName)  
 BEGIN  
   SET @newValueInt = CONVERT(int, @updateValue)
   UPDATE [dbo].[myTable] 
    SET [totalLeadTimeDays] = @newValueInt, [modifyDate] = GETDATE() 
    WHERE [inventoryID] = @updateInventoryID
 END

 IF('stockTakeETADate' = @fieldName)  
 BEGIN  
   SET @newValueDatetime = CONVERT(datetime, @updateValue)
   UPDATE [dbo].[myTable] 
    SET [stockTakeETADate] = @newValueDatetime, [modifyDate] = GETDATE() 
    WHERE [inventoryID] = @updateInventoryID
 END

 COMMIT

建议尝试/抓住