Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Concat String in SQL WHERE clause

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?

like image 884
Saquibul Islam Waheed Avatar asked Jul 22 '13 07:07

Saquibul Islam Waheed


People also ask

How do I concatenate a string to 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 I concatenate 3 columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

How do I concatenate 2 numbers in SQL?

Another way to implement Concat in SQL with the numerical value is to use the CAST operator. This operator converts the numerical data into the string format. Using the + (plus) operator will manipulate the numeric data into string concatenation.


2 Answers

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';
like image 148
Amir Hossein Jamsidi Avatar answered Oct 12 '22 23:10

Amir Hossein Jamsidi


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

like image 28
Madhivanan Avatar answered Oct 12 '22 23:10

Madhivanan