0

I am trying to use variables within my update statement but for some reason I don't understand it gives an error.

The following code works:

declare @sql nvarchar(max)
set @sql='update valuetable set waarde=(select top 1 firstname from DimEmployee where firstname not like ''%[0-9]%'' )'
exec (@sql)

If I change firstname and DimEmployee to variables using the following code:

declare @column nvarchar(max);
declare @table nvarchar(max);
declare @sql nvarchar(max)
set @column='firstname';
set @table='dbo.dimEmployee'
set @sql='update valuetable set waarde=(select top 1 '+ @column + 'from '+@table+' where '+@column+' not like ''%[0-9]%'')'
exec (@sql)

it gives the following error: Incorrect syntax near '.' on line 1

Could somebody explain to me what I'm doing wrong and if there's a fix for my problem?

1 Answer 1

1

You should print out the SQL to see what you are actually running. For instance, it is obvious that the lack of space before from is an issue:

set @sql = '
update valuetable
    set waarde = (select top 1 '+ @column + ' from ' + @table + ' where ' + @column + ' not like ''%[0-9]%'')
';
Sign up to request clarification or add additional context in comments.

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.