Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect Syntax Near '+' - SQL/TSQL

Trying to do this (in SQL Server Management Studio)

DECLARE @fun as int
SET @fun = 40
PRINT 'String' + 'Hello!'

EXEC msdb.dbo.sp_senddbmail
    @profile_name = 'Some working profile',
    @recipients = '[email protected]',
    @subject =  'String' + 'Hello!',
    @body = 'Test email sendout'

Getting this error :

Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '+'.

Notice the first concatenation works, second doesn't.

The steps I've taken:

Retyped it all out (so its not a copy paste error). Tried changing it to ('String' + 'Hello!') and get error Incorrect syntax near '('. So I'm feeling a bit lost.

EDIT 2: I've changed the example because the same error happens when its two strings, no casts involved

like image 327
Jono Avatar asked Jan 07 '15 18:01

Jono


People also ask

What does Incorrect syntax mean in SQL?

The most common SQL error is a syntax error. What does syntax mean? Basically, it means a set arrangement of words and commands. If you use improper syntax, the database does not know what you're trying to tell it.

Can we use not in WHERE clause in SQL?

The NOT IN operator can be used anywhere any other operator is used including WHERE clauses, HAVING clauses, IF statements, or join predicates – although they should be extremely rare in join predicates (SQL JOINS - SQL INNER JOIN, SQL LEFT JOIN, SQL RIGHT JOIN).

Can we use (+) in SQL Server?

You should not use (+) in Oracle. Use standard JOIN syntax.


Video Answer


2 Answers

Values passed to stored procedures parameters (in T-SQL) must be, umm, "single values" (can't think of the technical term just now). You cannot use code like:

@subject = A + B + C

you can only have code like

@subject = A

So in this case, you'd need something like:

DECLARE
  @fun      int
 ,@Subject  nvarchar(255)

SET @fun = 40

SET @Subject = 'String' + 'Hello!'

EXEC msdb.dbo.sp_send_dbmail  --  Added the second underscore...
    @profile_name = 'Some working profile',
    @recipients = '[email protected]',
    @subject = @Subject,
    @body = 'Test email sendout'
like image 61
Philip Kelley Avatar answered Nov 08 '22 23:11

Philip Kelley


try this, convert int value as varchar then concat with another varchar value

DECLARE @fun as int
SET @fun = 40
PRINT convert(varchar(10), @fun) + 'Hello!'

EXEC msdb.dbo.sp_senddbmail
@profile_name = 'Some working profile',
@recipients = '[email protected]',
@subject =  convert(varchar(10), @fun) + 'Hello!',
@body = 'Test email sendout'
like image 33
HaveNoDisplayName Avatar answered Nov 08 '22 22:11

HaveNoDisplayName