Home > Software design >  Concatenating single quote in where clause to a variable in T-SQL
Concatenating single quote in where clause to a variable in T-SQL

Time:09-06

I have a VARCHAR variable declared which I want to use in a where clause to search results with a specific phone number.

DECLARE @Phone VARCHAR(50) 
SET @Phone = 075000000

SELECT  * 
FROM my_table
WHERE phone = '''   @Phone   '''

but it does not return any result. It works when I use WHERE phone = '075000000' . I tried also WHERE phone = '''' @Phone '''' and WHERE phone = CHAR(39) @Phone CHAR(39) but still no results.

Also tried to declare @Phone as NUMERIC and converting it to string CONVERT(VARCHAR(50), @Phone) but still same issue.

phone column is a NVARCHAR(50), not null .

CodePudding user response:

Can you try

DECLARE @Phone VARCHAR(50) 
SET @Phone = '''075000000'''

SELECT  * 
FROM my_table
WHERE phone = @Phone

CodePudding user response:

Please try the following:

DECLARE @Phone NVARCHAR(50) 
SET @Phone = '075000000'

SELECT  * 
FROM my_table
WHERE phone = @Phone

@Stu has already provided the answer and the explanation in the comments section.

  • Related