I’d like to do the following in T-SQL:
EXEC('... ' + (SELECT ...))
A simple concrete example would be
EXEC('DROP TABLE ' + (SELECT name FROM sys.tables WHERE ...))
(Obviously, the WHERE clause is chosen such that the subquery always returns exactly one value.) When I try this, I get an error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'.
I know that I can work around this by using variables, e.g.:
DECLARE @sql varchar(MAX)
SELECT @sql = 'DROP TABLE ' + name FROM sys.tables WHERE ...
EXEC(@sql)
but for various reasons I’d like to have only one statement. Is that possible?
PS: In case it’s relevant, that’s the dynamic SQL code I’m trying to squeeze into one statement:
You can’t do treatment on the value that you pass to the EXEC function.
Thus, you can’t concatenate or otherwise transform the value, it as to be done prior to the call.
Thus the answer is, no you can’t.
But like Pondlife said, if you give the reason why you want to do it this way, it will be possible to find a more satisfying answer.