Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL select row into a string variable without knowing columns
    primarykey
    data
    text
    <p>I am new to writing SQL and would greatly appreciate help on this problem. :)</p> <p>I am trying to select an entire row into a string, preferably separated by a space or a comma. I would like to accomplish this in a generic way, without having to know specifics about the columns in the tables.</p> <p>What I would love to do is this:</p> <pre><code>DECLARE @MyStringVar NVARCHAR(MAX) = '' @MyStringVar = SELECT * FROM MyTable WHERE ID = @ID AS STRING </code></pre> <p>But what I ended up doing was this:</p> <pre><code>DECLARE @MyStringVar = '' DECLARE @SecificField1 INT DECLARE @SpecificField2 NVARCHAR(255) DECLARE @SpecificField3 NVARCHAR(1000) ... SELECT @SpecificField1 = Field1, @SpecificField2 = Field2, @SpecificField3 = Field3 FROM MyTable WHERE ID = @ID SELECT @StringBuilder = @StringBuilder + CONVERT(nvarchar(10), @Field1) + ' ' + @Field2 + ' ' + @Field3 </code></pre> <p>Yuck. :(</p> <p>I have seen some people post stuff about the COALESCE function, but again, I haven't seen anyone use it without specific column names.</p> <p>Also, I was thinking, perhaps there is a way to use the column names dynamically getting them by:</p> <pre><code>SELECT [COLUMN_NAME] FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyTable' </code></pre> <p>It really doesn't seem like this should be so complicated. :(</p> <p>What I did works for now, but thanks ahead of time to anyone who can point me to a better solution. :)</p> <p>EDIT: Got it fixed, thanks to everyone who answered. :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload