Given the following table:
USE tempdb;
CREATE TABLE #T(Val INT);
INSERT INTO #T VALUES (1), (2), (3), (4), (5);
I wanted to execute a dynamic sql query using EXEC
given a Val
value:
DECLARE @sql NVARCHAR(MAX);
DECLARE @Val INT = 3;
EXEC ('SELECT * FROM #T WHERE Val = ' + @Val);
This executes without error and gives the correct result.
My assumption is that this will produce an error:
Conversion failed when converting the varchar value 'SELECT * FROM #T WHERE Val = ' to data type int.
Since @Val
is of INT
data type and by the rules of the data type precedence, the query inside the EXEC
must be converted to INT
.
My question is why didn't the call to EXEC
produce a conversion error?
Notes:
- I know about sp_executesql
. I'm not also asking for an alternative. I'm just asking for an explanation why no error was produced.
- The answer to this question does not seem to explain my situation as the question refers to VARCHAR
to VARCHAR
concatenation.
EXEC
with multiple strings+
ed together that would have exceeded the 8000/4000 character limits for varchar/nvarchar at the time. Therefore, I believe that the+
inside anEXEC()
is not the standard string concatenation operator. Although the function is only specified to accept string data types, I'd guess that means it's going to stringify any non-string types and data precedence can go walk off a short pier. But this is just speculation, hence not an answer. – HermitINT
variable works. – EqualXML
, result: "Implicit conversion from data type xml to nvarchar is not allowed." – Equal+
withinEXEC
is only working with string types withdeclare @i int;declare @j int;select @i=1,@j=2;exec (@i+@j)
which produces "Incorrect syntax near '12'", so the original data types definitely don't matter. – HermitNVARCHAR
). It fails if no imlpicit conversion is allowed (see XML comment above). And if you specify a constant then compilation fails i.e. EXEC is not even executed. – Equal(N)VARCHAR
. And sinceINT
can be converted to(N)VARCHAR
, there is no error produced. Unlike with theXML
data type. If only there's a documentation somewhere. – Photosensitive