SQLServer multiple rows of data are combined into one line data (one field)

Requirements: There are four lines of data, as follows:

  1. Apple
  2. orange
  3. Peaches
  4. Polo

  Merged into a field: apples, oranges, peaches, Polo;

  After a clear demand, to get some test data on the code:

  

Copy the code
- Create a temporary table 
the Create the Table #temp 
( 
    TestName VARCHAR (20) 
) 

- written test data 
INSERT INTO #temp (testName) values ( ' Apple'); 
INSERT INTO #temp (testName) values ( ' orange') ; 
the INSERT the INTO #temp (TestName) values ( 'peach'); 
the INSERT the INTO #temp (TestName) values ( 'Polo'); 

- the data is written and 
the SELECT * #temp the FROM 
--delete #temp
Copy the code

 

After the demo data populated, there are several ways we can achieve requirements:

One:

DECLARE @listStr VARCHAR(MAX);
SELECT @listStr = ISNULL(@listStr+',','')+ testName
FROM #temp
SELECT @listStr

In the above script code used ISNULL function, may be used Coalesce function, these two functions have null strings in the case of treatment, the difference deeper reference herein ;

So the question is, why should I use ISNull or Coalesce function? This is because all of the data row if you do not rule out the possibility of null values, plus the best deal null value judgment, because in SQLSERVER, if the need for string concatenation, nulls are encountered words can not be spliced.

 

II: Use for xml path ( '') and Stuff;

    SELECT ',' + testName 
    FROM #temp for xml path('')

 

3: Use string functions STRING_AGG, this function is only after SQLSERVER 2017.

STRING_AGG the SELECT (the ISNULL (TestName, 'N / A'), ',') 
the FROM #temp 

query result: apples, oranges, peaches, N / A, Polo

 

Guess you like

Origin www.cnblogs.com/bdqczhl/p/11665818.html
Recommended