Serial Number with COALESCE function

Posted on 2013-11-10
Last Modified: 2013-11-16
Dear all,
I use The following :
DECLARE @Names VARCHAR(8000) ;DECLARE @i int=0; 
SELECT top 10 @Names = COALESCE(@Names +', ', '') + '[' + COLUMN_NAME+  ']' 
FROM dbo.site_DatabaseFields
where TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME  = 'JDB.dbo.Invoices'

Open in new window

To Generate :
[AccNo], [Attach], [BankName], [Branch], [BranchSer], [CName], [City], [CriditPeriod], [CusPO], [DiffDay]

Open in new window

I need to generate :
[AccNo] as Field1, [Attach] as Field2, [BankName] as Field3, [Branch] as Field4, [BranchSer] as Field5, [CName] as Field6, [City] as Field7, [CriditPeriod] as Field8, [CusPO] as Field9, [DiffDay] as Field10

Open in new window

Question by:ethar1
LVL 35

Accepted Solution

Robert Schutt earned 500 total points
ID: 39636691
Try this:
DECLARE @Names VARCHAR(8000) ;DECLARE @i int=0; 
SELECT top 10 @i = @i + 1, @Names = COALESCE(@Names +', ', '') + '[' + COLUMN_NAME+  '] as Field' + CONVERT(varchar, @i) 
FROM dbo.site_DatabaseFields
where TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME  = 'JDB.dbo.Invoices'

Open in new window

LVL 48

Expert Comment

ID: 39637575
just as a tip, you can use QUOTENAME

SELECT top 10 @Names = COALESCE(@Names +', ', '') + QUOTENAME(COLUMN_NAME)

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how the fundamental information of how to create a table.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question