Monthly Archives: August 2013

Execute an sql query as string using sp_executesql and store the result in a variable

Small but useful tip for Sql Server 2012.

Here is a simple example for how we can execute an sql string query, execute it and store the result in a variable for further use.

declare @query nvarchar(1000), @result datetime

set @query = ‘select @result = GETDATE()’

EXEC sp_executesql @query,
N’@result datetime OUTPUT’,
@result OUTPUT

print CAST(@result as nvarchar(100))