0

I'm a beginner to SQL Server

I wrote this query:

DECLARE @sql nvarchar(1000) = 'UPDATE Work
                               SET [Name] = Programmer, [ImageAddress] = pic.jpg 
                               WHERE Id = 2'

SELECT @sql
EXEC Sp_executesql @sql

but I get this error

Invalid column name 'Programmer'.

Why do I get this error?

Thank you for your help

2 Answers 2

1

You are dealing with SQL in strings. Quoting the strings becomes a challenge. You need for Programmer to be in single quotes when the query is executed. To get this, you need double single quotes in the string:

DECLARE @sql nvarchar(1000)='
UPDATE Work
    SET [Name] = ''Programmer'', [ImageAddress] = ''pic.jpg'' WHERE Id=2'

select @sql

EXEC Sp_executesql @sql;

Because you are wise enough to use sp_executesql, you should learn about parameters. You can write the query as:

DECLARE @sql nvarchar(1000)='
UPDATE Work
    SET [Name] = @Programmer, [ImageAddress] = @imageaddress WHERE Id=2'

select @sql

EXEC Sp_executesql @sql, N'@programmer nvarchar(255), @imageaddress nvarchar(255)',
     @programmer = N'Programmer', @imageaddress = N'pic.jpg';

This has several advantages besides the quoting. It is safer in terms of SQL injection and it allows SQL Server to cache the execution plans if the query is called more than once.

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

2 Comments

thank you for your answer, but one other question, if i want pass variable instead of string into column value, how i can do it? like this SET [Name] ='+@Name+',
@sqlDev . . . Yes. And in that case I would strongly encourage you to use parameter substitution instead of constructing the values in the string.
0

try this:

You need to use '' (Double Quotes for string) Inside Dynamic SQL

DECLARE @sql nvarchar(1000)='

    UPDATE Work

        SET [Name] = ''Programmer'',[ImageAddress] =''pic.jpg'' WHERE Id=2'

    select @sql

EXEC Sp_executesql @sql

Comments

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.