13

I have declared two variables in RAW sql

DECLARE @str nvarchar(max), @str1 nvarchar (max);

SET @str = "  AND (c.BondSales_Confirmed <> -1)";

SET @str1 = "  AND (c.BondSales_IssueType = 'REGULAR')";

My SQL query is:

SELECT * From t_BondSales Where (BondSales_cType <> 'Institute') " + str1 + str  "

Here I get the following error:

Error: SQL Problems: Incorrect Syntax near "+ str1 + str"

Can any one Please help me with the proper syntax about how to concat String in where clause?

1
  • 2
    It was showing you error just because you left "@" symbol before your variable names in the select query. Commented Jul 22, 2013 at 7:26

3 Answers 3

22

very easy!! in mysql use CONCAT() function:

SELECT * FROM tbl_person WHERE CONCAT(first_name,' ',last_name) = 'Walter White';

but this does not work in mysql:

SELECT * FROM tbl_person WHERE first_name+' '+last_name = 'Walter White';
Sign up to request clarification or add additional context in comments.

2 Comments

The CONCAT(first_name, ' ', last_name) = '' one works with JPA TypedQuery too. Thank you for your help.
The question is about MS SQL Server
11

Try this one -

DECLARE 
       @str NVARCHAR(MAX)
     , @str1 NVARCHAR (MAX);

SELECT 
       @str = ' AND c.BondSales_Confirmed != -1'
     , @str1 = ' AND c.BondSales_IssueType = ''REGULAR''';

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = '
SELECT * 
FROM t_BondSales 
WHERE BondSales_cType != ''Institute'''
     + @str 
     + @str1

PRINT @SQL
EXEC sys.sp_executesql @SQL

2 Comments

Can you suggest me another last thing, which is: Is this String concatenation is supported in Jasper (iReport)? @Devart
Sorry, but I don't know exactly about that. Possibly - yes.
2

Passing column names along with values is subject to SQL Injection. Make sure to read this post www.sommarskog.se/dynamic_sql.html

So I would suggest you to change the code like this

declare @BondSales_Confirmed int
declare @BondSales_IssueType varchar(100)

SELECT * From t_BondSales Where (BondSales_cType <> 'Institute')
AND (c.BondSales_Confirmed <> @BondSales_Confirmed  or @BondSales_Confirmed is null)
AND (c.BondSales_IssueType = @BondSales_IssueType or @BondSales_IssueType is null)

Just pass null value if you do not want to apply a condition to the columns BondSales_Confirmed and BondSales_IssueType

1 Comment

This doesn't serve my purpose actually. Thanks anyway @Madhivanan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.