Created
October 1, 2018 19:34
-
-
Save aevdokimenko/0bcd95ac1de8f3d5b33b77831d619743 to your computer and use it in GitHub Desktop.
Usage of sp_executequitedsql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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