Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


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

Posted on 2016-08-03
Medium Priority
Last Modified: 2016-10-08
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.
Question by:cautrey
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 2
  • 2
  • +2
LVL 17

Expert Comment

by:Barry Cunney
ID: 41740632
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

LVL 13

Expert Comment

ID: 41740646
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?
LVL 66

Expert Comment

by:Jim Horn
ID: 41740713
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

LVL 41

Expert Comment

ID: 41740733
You may need PIVOT kind of solution. Do you know how many max columns can be generated? Provide some sample data and expected output.

Author Comment

ID: 41740736
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

Author Comment

ID: 41740780
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.
LVL 66

Expert Comment

by:Jim Horn
ID: 41740784
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.

Author Comment

ID: 41740946
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.

Author Comment

ID: 41741371
Is there anyone available to help with this?
LVL 41

Accepted Solution

Sharath earned 2000 total points
ID: 41741879
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 '],[' +
                           from    Source_Table as t2
                          order by '],[' +
                            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


Author Comment

ID: 41742828
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.

Author Comment

ID: 41743102
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.

Author Comment

ID: 41743354
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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Ready to get certified? Check out some courses that help you prepare for third-party exams.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question