Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate string when setting a parameter in Transact-SQL

Tags:

First question here and is the following. I wrote the following code and everything works fine:

DECLARE @subject NVARCHAR(100) SET @subject = 'Report executed on ' + CONVERT(VARCHAR(12), GETDATE(), 107) SELECT @subject 

Result: Report executed on Aug 17, 2012

but when trying to concatenate the previous string while setting the parameter of msdb.dbo.sp_send_dbmail procedure, it fails

EXEC msdb.dbo.sp_send_dbmail @profile_name='XXX', @recipients='[email protected]', @subject = 'Report executed on ' + CONVERT(VARCHAR(12), GETDATE(), 107), @body= @tableHTML, @body_format = 'HTML'; 

I know I could declare and send a variable to the parameter but I would like to understand why it fails when concatenating directly in the parameter. thank you for your time and knowledge

like image 810
ChuyTM Avatar asked Aug 17 '12 16:08

ChuyTM


People also ask

How do I concatenate a string with a variable in SQL Server?

Concatenates two strings and sets the string to the result of the operation. For example, if a variable @x equals 'Adventure', then @x += 'Works' takes the original value of @x, adds 'Works' to the string, and sets @x to that new value 'AdventureWorks'.

How do you concatenate strings and variables?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.


2 Answers

Parameter values to T-SQL stored procedures cannot be expressions. They need to be either a constant or a variable.

From MSDN - Specify Parameters:

The parameter values supplied with a procedure call must be constants or a variable; a function name cannot be used as a parameter value. Variables can be user-defined or system variables such as @@spid.

like image 73
Kash Avatar answered Sep 22 '22 19:09

Kash


You need to do:

DECLARE @Sub nvarchar(100); SET @Sub = 'Report executed on ' + CONVERT(VARCHAR(12), GETDATE(), 107); EXEC msdb.dbo.sp_send_dbmail @profile_name='XXX', @recipients='[email protected]', @subject = @Sub, @body= @tableHTML, @body_format = 'HTML'; 
like image 32
Hannah Vernon Avatar answered Sep 19 '22 19:09

Hannah Vernon