I have a table dbo.t_products and I want to know the last record updated. For that I have an attribute last_changed which stores for each record the timestamp of the last update.
Finally I want to save that result in a variable called @y.
DECLARE @y DATETIME
DECLARE @p_table VARCHAR(100)
SET @p_table = 'dbo.t_products'
EXECUTE sp_executesql N'SET @y = SELECT MAX(last_changed) FROM @p_table'
,N'@p_table VARCHAR, @y DATETIME OUTPUT'
,@p_table
,@y OUTPUT
SELECT @y
The system returns the following message:
Msg 156, Level 15, State 1, Line 25
Incorrect syntax near the keyword 'SELECT'.
Any ideas?
The whole point of using dynamic SQL in your case (I assume) is to allow the use of a dynamic table name. In which case you have to insert the table name into the dynamic SQL string - you can't pass it in as a parameter, thats the problem you are trying in the first place.
Also you don't need a
SETfollowed by aSELECTjust useSELECTdirectly to set the variable.Finally you definitely want to use the
QUOTENAMEfunction to escape your table name and avoid an SQL injection attack - this requires you split the table name and schema name.