Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server EXEC with unquoted string parameter is valid?

Tags:

sql-server

By accident I called a stored procedure with an unquoted string parameter. I expected a syntax error as per:

EXECUTE (Transact-SQL)

If the value of a parameter is an object name, character string, or qualified by a database name or schema name, the whole name must be enclosed in single quotation marks.

but this works:

CREATE PROC foobar @a VARCHAR(40) AS BEGIN SELECT @a END
go
EXEC foobar @a = abc

Which surprised me! I tried on SQL Server versions 2008, 2012 and 2016. Am I missing something or is this just an undocumented "feature"?

like image 982
user1443098 Avatar asked Jul 23 '26 05:07

user1443098


1 Answers

MS are aware, and their comments on this post imply that this is by design:

SQL Server automatically converts “single-word identifiers” to string literals if they are provided as NVARCHAR parameters in stored procedure calls. Therefore these statement will work fine:

EXEC dbo.TestProc foo
EXEC dbo.TestProc "foo"
EXEC dbo.TestProc [foo]

and they are equivalent to:

EXEC dbo.TestProc 'foo'

However, it does not convert identifiers to string literals in SELECT and assignments.

However, I can't think of any situation where it would be appropriate to use this (aside from testing for vulnerabilities which exploit this feature, or in writing code to execute user-provided queries which you wish to provide full language support for, including quirks.

The best advise is to be aware that this is possible (so you don't rule out the possibility of it working when writing tests / debugging code / checking for potential exploits), but do not make use of this behavior in your own code.

like image 62
JohnLBevan Avatar answered Jul 26 '26 20:07

JohnLBevan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!