Table: I have a database table table_1 in SQL Server 2012 with data as:
CREATE TABLE table_1
(
name nvarchar(128) not null,
state tinyint null,
state_desc nvarchar(60) null
);
INSERT INTO table_1
VALUES ('text1',1,'ONLINE'),
('text2',0,'ONLINE'),
('text3',0,'ONLINE'),
('text4',0,'ONLINE'),
('TEXTTE',0,'ONLINE'),
('TEXTTEXT',0,'ONLINE'),
('EXTTEXT',0,'ONLINE'),
('TEXTex_EX_Ext',0,'ONLINE'),
('TEXTex_TEX_Ext',0,'ONLINE'),
('TEXTTEXTText',0,'ONLINE'),
('Texttextext',0,'ONLINE'),
('TextTextext',0,'ONLINE'),
('TEXTER',1,'ONLINE');
I want to select all the values in column state and concatenate them to get a single string.
So desired result is a single row and a single column with data as:
1000000000001
What I have tried: Using substring but it skips first row (1) and gives 13 rows (000000000001 in each row) instead of just 1.
Select
substring(
(
Select ''+ST1.[state] AS [text()]
From dbo.table_1 ST1
For XML PATH ('')
), 2, 1000) [state]
From dbo.table_1 ST2;
Is there any other way to do this?
I will not know the number of rows and I want to keep the sequence while concatenating. (First row should be first digit, second row second digit, etc)
It doesn't matter if the first row goes rightmost or leftmost after concatenation, just it needs to be consistent and in sequence.