0

I am passing dynamic column name base that column name to Update the value and below i my table

Table_CandidateInfo

Id     Name        Age    City 

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar

Example1

Declare @ColumnName varchar(100), @Id int

set @ColumnName='City' 
set @Id=20
set @value='Hyderabad'

update set ____ Table_CandidateInfo where ID=@Id 

my output should like below Table_CandidateInfo, Hyderabad City updated base on Id and Column name

Table_CandidateInfo

Id     Name        Age    City 

1      Mazhar      30     Gulbarga

20     Khan        29     Hyderabad

Column name is dynamic some time @ColumnName='Name' so name value should update

Yesterday i have asked for get data base on column value that working fine but now i need to update

How to get value by dynamic field Name using sql select query

2
  • Read about dynamic SQL in SQL Server: mssqltips.com/sqlservertip/1160/… Commented May 28, 2019 at 5:55
  • let it be can you answer. @TimBiegeleisen Commented May 28, 2019 at 5:58

1 Answer 1

1

Well, since you can't parameterize identifiers in SQL, your only option would be to use dynamic SQL for such things.
However, please note that the code that creates and execute the dynamic SQL statement needs to be written in such a way it would prevent SQL injection attacks.
The rule is quite simple - what you can't parameterize must be white-listed.

So basically, you can do something like this:

CREATE PROCEDURE UpdateCandidateInfo
(
     @ColumnName sysname, 
     @Id int,
     @value sql_Variant
)

AS

IF EXISTS
(
    SELECT 1
    FROM information_schema.columns
    WHERE Table_Name = 'Table_CandidateInfo'
    AND Column_Name = @ColumnName
)

BEGIN

    DECLARE @Sql nvarchar(4000) = N'Update Table_CandidateInfo SET '+ QUOTENAME(@ColumnName) + N' = @Value WHERE Id = @Id';

    DECLARE @Params nvarchar(4000) = N'@Value sql_Variant, @Id int'

    EXEC sp_ExecuteSql @Sql, @Params, @Value, @Id
END

GO

Please note that the code was written directly here and therefor untested - there might be mistakes in it but that's the general idea.

sysname is a system data type which is used by SQL server for all identifiers. It's basically an alias to nvarchar(128), except it's non-nullable.

sql_variant is a special data type which can be used to hold different data types inside.

use QUOTENAME to enable the use of column names containing spaces, dots, or that are reserved keywords.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.