SQL Query: How to include single inverted comma in a query

1st Method:
Declare @Customer varchar(255),
@sqlstring varchar(4000)
Set @Customer = ‘Customer_Name’

set @sqlstring = ‘Select Customerid from Customer Where name = ‘ + @Customer + 
print @sqlstring

Output is:
Select Customerid from Customer Where name = ‘Customer_Name’
Note:
Actually to include a ‘ inverted comma in the search you just add one more extra ” inverted comma in front of it.

So where name =’Joshua’ is will search for string Joshua, to search for string ‘Joshua’ including single inverted comma, we first add the single inverted comma to include in the search and then one more as a escape character, so it will be where name=”’Joshua”’ which will search for string ‘Joshua’.

If you look closely @sqlstring = ‘Select Customerid from Customer Where name = ‘ + @Customer + ” you will see after name there are three single inverted comma and after @Customer there are four single inverted comma. So, how come? Lets break down this. Our target string would be –

Select Customerid from Customer Where name = ‘Customer_Name’ 
So according to rule lets add one more extra comma single inverted comma 
Select Customerid from Customer Where name = ”Customer_Name”

now to take the Customer_Name as parameter
set @sqlstring = ‘Select Customerid from Customer Where name = ‘‘ ‘ + @Customer + ‘ ‘‘ ‘

one single inverted comma for the beginning of the string and one single inverted comma for the end the string. so to include two inverted comma, it would ””
  

2nd method:
select quotename(Customer_Name,””)

Leave a comment