[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 68
  • Last Modified:

How can I select multiple values and insert them into a single row In MS SQL

In MS SQL I need to select particular values by name from a table and insert them into a single row in another table.

In a real basic sense I need this but 10+ results into a 10+ column row with a date/time reference.
Insert into [table2].[namealias1]
    Select [number] as namealias1 
    From [db].[table]
    Where [name] = 'name1'

Open in new window

Table1 (source)

Table2 (destination)
DATESTAMP  NameAlias1 NameAlias2

Or is this the best way to even think about it?
The end goal is to record the specific values with a time stamp in a single row in another table.
  • 7
  • 2
  • 2
  • +2
1 Solution
Barry CunneyCommented:
Hi Cautrey,
Please try something similar to the following:
Insert into [table2] (DATESTAMP, [namealias1], [namealias2]
         ,[number] as namealias1
         ,'' AS namealias2
    From [db].[table]
    Where [name] = 'name1'
        ,'' AS namealias1
         ,[number] as namealias2 
    From [db].[table]
    Where [name] = 'name2'

Open in new window

Not knowing the exact number of rows that you're dealing with makes it a lot more complicated, especially since the number of rows is what's going to drive the number of columns in your destination table (if I understood correctly).

Is this a one-time thing? Or are you trying to automate an existing ETL process of some sort?
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Here's an article on how to pull that off in T-SQL using XML..
T-SQL:  Normalized data to a single comma delineated string and back
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

SharathData EngineerCommented:
You may need PIVOT kind of solution. Do you know how many max columns can be generated? Provide some sample data and expected output.
cautreyAuthor Commented:
It is going to be about 20 rows out of 200+ in the table.
It needs to be run every 12 hours.
We are recording particular values from a process to track changes.

I created the destination table already
cautreyAuthor Commented:
Hopefully the formatting makes sense.

I could probably pull the whole thing into a temp table. It is 200 rows and may end up 1000 max.
I need 20 or so specific values recorded from that table.

So an alias for the name field needs to be the column name and the value goes in the field.

Source Table
name   value
abc      12345
xyz       56789
def       25410

Result Table
Date                           north    south     east
08/03/2016 07:00    12345    56789    25410

Thanks everyone for any help or hints you can provide.
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Got it.  Disregard my comment about the article, as that's now not the question, as essentially you're asking for an Excel Transpose, and other experts are helping you out there.
cautreyAuthor Commented:
I am thinking of a query to create a derived table, a series of select statements against that table to assign variable names to the desired values, and then a insert into using those assigned variables.

Does this make sense?

I tried with a cte but the second select fails.
cautreyAuthor Commented:
Is there anyone available to help with this?
SharathData EngineerCommented:
Check this. Replace table/column names with your actual table and column names. Hope you will get an idea and modify as per your need.
--CREATE TABLE Source_Table (name VARCHAR(100), Value INT, Date1 DATETIME)
--INSERT Source_Table VALUES ('north',12345,'2016-08-03'),('south',56789,'2016-08-03'),('east',25410,'2016-08-03')

declare @cols nvarchar(2000)
 select  @cols = stuff(( select distinct top 100 percent '],[' + t2.name
                           from    Source_Table as t2
                          order by '],[' + t2.name
                            for xml path('')), 1, 2, '') + ']'

declare @query nvarchar(4000)
set @query = '
select Date1,' + @cols + '
  from (select name,Value,Date1 from Source_Table) as t1
pivot (sum(Value) for name in (' + @cols + ')) as p order by Date1'
print (@query)

-- Date1	east	north	south
-- 2016-08-03 00:00:00.000	25410	12345	56789

Open in new window

cautreyAuthor Commented:
Thanks Sharath!

That definitely gives me something to work with.

I don't need to declare the column names if I am just getting the values and inserting into an existing table right? If the values are queried in the correct order they can just be assigned to the destination columns in order? and for the date I just need a GETDATE in the insert right?

The problem I am running into is I have a lot of sub queries from the same column in the source.
I can UNION them into a single column but I not sure how to call them in the insert statement.
cautreyAuthor Commented:
I am still not getting it.

This is my output from my multiple select statements with UNION

How do I get these values into the table? It seems like they just need to read out with commas between them and stuck into a insert-value statement.
This is the destination table:
ID | TimeStamp | NorthTower | SouthTower | Sump | Barren | St2Plant | St2Heap | St3Plant | St3Heap | St4Heap | St4Plant | SumpRec

I just need a generate unique ID and the one record of the time when inserted.
Can I assign the output of the select as variable, derived table, or an xml file insert commas and reference in the insert statement?
We will always know the number of rows because we have that number of select statements with 1 result each.

Sorry but I am a complete novice at sql and got thrown into this task .
Appreciate any help I can get.
cautreyAuthor Commented:
Got it figured out. I just brute forced it.

Since I am using individual select statements from a single column anyway I just declared variables for each one and used them in the insert.

declare @north as int set @north = (select [value] from [source table] where [name] = 'name1')
declare @south as int set @south = (select [value] from [source table] where [name] = 'name2')
declare @east as int set @east = (select [value] from [source table] where [name] = 'name3')

Insert into [dest_table] (ID,Time,north,south,east)
 Value (NEWID(),GETDATE(),@north,@south,@east)

Open in new window

Thanks everyone

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 7
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now