T-Sql Select and combine many rows and columns into one row and one column

Basically, I wanted to return only one row and one column of the result from the stored procedure.

For example, my sample data and table look like this:

ColoumA INT ColoumB INT ColoumC NVARCHAR(MAX) ColoumA ColoumB ColoumC 1 1 ErrorMessage1 2 2 ErrorMessage2 3 3 ErrorMessage3 

After I successfully completed the successfully saved procedure, If Successful, the return result is a string value that combines all the details above. Such as

Or in another Word, I wanted to save all the value in TBL.rows[0][0]

in c # .net when i call the code

 String ReturnValue = ""; Datatable tbl = new Datatable(AREA); ReturnValue = tbl.Rows[0][0].ToString().Trim(); Console.Writeline("Sample Output"); Console.Writeline(ReturnValue); 

I was expecting something like this:

 Sample Output ColoumA: 1, ColoumB 1, ErrorMessage1 ColoumB: 2, ColoumB 2, ErrorMessage2 ColoumC: 3, ColoumC 3, ErrorMessage3 

Can I make a selection using T-Sql Statment? And if it can be done? how can i get it?

Hope someone can understand and answer my question.

Thanks:

PS: Sorry for my bad English Explanation

+4
source share
1 answer

My strong recommendation here would be: no need. Access it in the form of a grid (regular SELECT ) and do any processing in your application, i.e.

 var sb = new StringBuilder(); using(var reader = cmd.ExecuteReader()) { while(reader.Read()) { sb.Append("ColoumA: ").Append(reader.GetInt32(0)) .Append(", Coloum B").Append(reader.GetInt32(1)) .Append(", ").Append(reader.GetString(2)).AppendLine(); } } string s = sb.ToString(); 

However, you can do this in TSQL via:

 declare @result varchar(max) = '' select @result = @result + 'ColoumA: ' + CONVERT(ColoumA, varchar(10)) + ', ColoumB ' + CONVERT(ColoumB, varchar(10)) + ', ' + ColoumC + ' ' -- newline! from ... select @result 

the select @result = @result + ... pattern select @result = @result + ... does pretty much what you describe.

+3
source

Source: https://habr.com/ru/post/1381857/


All Articles