Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select column with row number concatenated in SQL Server

I am using SQL Server 2014 and want to select a column in a table with the row number concatenated to the column value in the result set.

For example:

DemoField
---------
Apple
Ball
Cat

Should return this result set:

DemoField
---------
Row1 Apple
Row2 Ball
Row3 Cat

I went through a few similar questions where ROW_NUMBER() is used, but I find that it is selected as a separate column and not concatenated to an existing column being returned.

When I try to concatenate the ROW_NUMBER() to the column, I get an error:

Error converting data type varchar to bigint.

Please let me know.

Thanks

like image 910
Vishwas Avatar asked Jan 01 '26 15:01

Vishwas


2 Answers

If 2012+ you can use concat()

Example

Declare @YourTable Table ([DemoField] varchar(50))
Insert Into @YourTable Values 
 ('Apple')
,('Ball')
,('Cat')

Select concat('Row',Row_Number() over(Order By DemoField),' ',DemoField)
 from @YourTable

Returns

(No column name)
Row1 Apple
Row2 Ball
Row3 Cat
like image 53
John Cappelletti Avatar answered Jan 03 '26 08:01

John Cappelletti


This is just basic ROW_NUMBER with some concatenation. Seems the desired output is pretty strange but the concept is simple.

select DemoField
from
(
    select DemoField = 'Row' + convert(varchar(4), ROW_NUMBER() over (order by DemoField)) + ' ' + DemoField
    from YourTable
) x
like image 35
Sean Lange Avatar answered Jan 03 '26 10:01

Sean Lange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!