Scenario:
Need to pass n arguments to a stored procedure. One of the arguments is of type varchar(x)
. That varchar argument needs to be constructed from a handful of other varchar variables. This problem uses SQL Server 2005, but this behaviour applies to all versions of SQL Server.
Setup:
DECLARE @MyString varchar(500), @MyBar varchar(10), @MyFoo varchar(10)
SELECT @MyBar= 'baz '
SELECT @MyFoo= 'bat '
-- try calling this stored procedure!
EXEC DoSomeWork @MsgID, 'Hello ' + @MyBar + '" world! "' + @MyFoo + '".'
This produces the exception in SQL Server: Incorrect syntax near '+'
. Typically you might think that the datatype would be wrong (i.e. the variables are of different types, but that would produce a different error message).
Here's a correct implementation that compiles without error:
SELECT @MyString= 'Hello ' + @MyBar + '" world! "' + @MyFoo + '".';
EXEC DoSomeWork @ID, @MyString
Question: Why is it that T-SQL can't handle the concatenation of a varchar as an argument? It knows the types, as they were declared properly as varchar.