简体   繁体   中英

Can I pass column name as input parameter in SQL update in stored procedure

CREATE PROCEDURE [dbo].[AddtoCurrent]
    @devname varchar(50),
    @currentmonth datetime,
    @ErrorType int,
    @ErrorTimes int
AS
BEGIN  
    UPDATE IssueLogByType
    SET  @ErrorType =  @ErrorType +  @ErrorTimes 
    WHERE Name = @devname  AND Month = @currentmonth
END

In this, @ErrorType is the column name. However in the database, this is saved as an int

Here is an example of a working statement

UPDATE IssueLogByType
SET Link =  Link +  @5
WHERE Name = 'John Doe' AND Month = 'January'

Is there a way to pass column name as input parameter in SQL update in this stored procedure?

You can't pass a column name as parameter BUT you can make a workaround and get your problem solved by using dynamic sql .

Basically, you write your sql as an string and then execute it. Here's an example using Oracle PL/SQL.

create or replace procedure prc_example_dynamic_sql(pc_column_name in varchar2
                                                   ,pc_column_value in varchar2
                                                   ,pc_primary_key in number) is
  --
  v_query varchar2(2000);
  --
begin
  --
  v_query := 'update my_table set ' || pc_column_name || ' = :p_value where my_id = :p_id';

  execute immediate v_query using pc_column_value, pc_primary_key;
  --
end prc_example_dynamic_sql;

Keep in mind that this solution can be a security issue because of SQL Injection so make sure to bind the values provided by users and concat the column name only if its values does not come from user input.

Also seems like your example was using SQL Server so here is a good tutorial about how to use dynamic sql.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM