Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@aevdokimenko
Created October 1, 2018 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aevdokimenko/0bcd95ac1de8f3d5b33b77831d619743 to your computer and use it in GitHub Desktop.
Save aevdokimenko/0bcd95ac1de8f3d5b33b77831d619743 to your computer and use it in GitHub Desktop.
Usage of sp_executequitedsql
-- Paramertizing a call to sp_executesql
Declare @sql nvarchar(max)
declare @par1 int, @par2 nvarchar(255), @par3 datetime
select @par1 = 5, @par2 = 'K%', @par3 = GETDATE()
-- Doubling double single quotes
select @sql = '
select *
from openquery(LINKEDSERVER, ''
select *
from Employees
where
YearsInCompany > ' + str(@par1) + '
and LastName like ''''' + @par2 + '''''
and HireDate > ''''' + cast(@par3 as varchar(20)) + '''''
limit 10'')'
print @sql
--exec sp_executesql @sql
-- Same but for sp_executequotedsql
select @sql = '
select *
from openquery(LINKEDSERVER, `
select *
from Employees
where
YearsInCompany > ' + str(@par1) + '
and LastName like "' + @par2 + '"
and HireDate > "' + cast(@par3 as varchar(20)) + '"
limit 10`)'
-- Omit the second parameter if you trust the code
exec sp_executequotedsql @sql, @debug = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment