Scripting Variable in String
-
Wednesday, June 13, 2012 7:06 AM
Hi Community,
Is it possible to intergrate variables in string? (Without concate symbol). This is much better for reading code.
This is possible in PHP Language for example.
$MyVar = "World"; $string = "Hello $MyVar";
// another method
$string2 = sprintf("Hello %s", $MyVar);
Or is there something similar in T-SQL Language?
All Replies
-
Wednesday, June 13, 2012 7:15 AM
Hello,
In T-SQL? Not really, you would have to replace the value:
DECLARE @MyVar varchar(100); SET @MyVar = 'World'; DECLARE @string varchar(100); SET @string = 'Hello @MyVar'; SET @string = REPLACE(@string, '@MyVar', @MyVar); SELECT @string
Olaf Helper
* cogito ergo sum * errare humanum est * quote erat demonstrandum *
Wenn ich denke, ist das ein Fehler und das beweise ich täglich
Blog Xing -
Wednesday, June 13, 2012 7:34 AM
Hi,
depends on where you want to apply this! In case of dynamic sql using sp_executesql you can have a similar behavior(not exactly the same however).
Regards
satheesh -
Wednesday, June 13, 2012 7:35 AM
No. String processing is not a strong point of T-SQL.
Then again, you don't have reason to do this too often in T-SQL. If you are thinking of dynamic SQL, the answer is that you should use parameterised SQL. I discuss this in my article on dynamic SQL on
http://www.sommarskog.se/dynamic_sql.html
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se- Marked As Answer by robie2011 Wednesday, June 13, 2012 9:30 AM
-
Wednesday, June 13, 2012 9:27 AMThis is an very interesting article ... thank you
-
Wednesday, June 13, 2012 9:28 AMBad for me. Not very casual for coding :-)
-
Wednesday, June 13, 2012 9:28 AMI think, dynamic SQL will work for me.

