9

How to concatenate a column value with single quotes and a comma in sql?

select tpaa_id  from dbo.Sheet
where tpaa_id is not null

At present query returns, value as ..

ABC123
ABC456

We have around 1000 records.

I expect to return as

'ABC123',
'ABC456',
goofyui
  • 3,362
  • 20
  • 72
  • 128

8 Answers8

7

Use this construction

SELECT CONCAT(CHAR(39), MyString ,CHAR(39)) FROM Table

return '<MyString>'
Iñigo
  • 1,877
  • 7
  • 25
  • 55
Jiri
  • 71
  • 1
  • 1
6

You can use variable for concatenation:

declare @result nvarchar(max)

select @result  = isnull(@result + ', ', '') + '''' + tpaa_id  + '''' 
from dbo.Sheet
where tpaa_id is not null

select @result
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
2

You can simply concatenate the columns using the query

select ''''||tpaa_id||''''||','  from dbo.Sheet
where tpaa_id is not null;
afxentios
  • 2,502
  • 2
  • 21
  • 24
2

To get the values with comma , use below statement...

select field 1 || ',' from table name;

  • Thank you Bhargav,I wasn't aware of pipeline syntax in the select query. I will do that. Thank you again :) – goofyui Mar 10 '20 at 16:20
1

If its SQL Server 2017 and above

SELECT STRING_AGG(QUOTENAME(tpaa_id,''''), ',') FROM dbo.Sheet

user1242496
  • 139
  • 2
  • 8
0

Use three single quotes to concatenating

select  'insert into [LookUpModeofTransfer] values('''+Name+'''' +',1'+')'  from 
(SELECT  name,isActive FROM [dbo].[LookUpModeofTransfer]
 )a
Hari Lakkakula
  • 199
  • 1
  • 4
0

when we do String Concatenation in sql we need to use ISNULL function----------------

DECLARE @str1 NVARCHAR(20)
DECLARE @str2 NVARCHAR(20)
SET @str1 = NULL
SET @str2 = 'str2'
select @str1 + @str2
select ISNULL(@str1,'') + ISNULL(@str2,'')
hotfix
  • 3,376
  • 20
  • 36
Elias
  • 11
  • 2
-1

hi 
'UPDATE LinkedMySQLDB.TableToUpdate AS a SET a.MySQLField=''updated'' WHERE a.ID IN (LocalMSSQLDB.LocalTable.ID) ;' 

This is a string constant but you need a value for LocalMSSQLDB.LocalTable.ID.

Declare @ldb int;
set @ldb = select LocalMSSQLDB.LocalTable.ID

'UPDATE LinkedMySQLDB.TableToUpdate AS a SET a.MySQLField='' + value + '' WHERE a.ID IN (' + @ldb + ') ;'
LDS
  • 354
  • 3
  • 9