SQL-Multiple Insert into identity table - sql

I need to to do a insert from a table with the following structure:
Table A
Col1 Col2 Col3 Col4
intID1 intID2 intID3 intID4
I need to select the rows from the above table that are null
for col1,col2,col3 and insert those rows into a table that will generate an identity
row that I need to use to insert into another table.I am not sure of the
sql statement or the general method used to select those rows and insert them multiple times and retrieve the identity id one by one to insert into the next table.
Any help is greatly appreciated!
Sample process:
Table A
Col1 Col2 Col3 Col4
1 3 7 null
null null null 45
null null null 67
1)Retrieve rows 2 and 3
2)Insert 2 and 3 into another table to retrieve identity id for both rows
3)Insert identities from step 2 into another table

Venk covered step 1 and 2 I think. For 3 can use the OUPUT clause to retrieve the identity value from set operation.
Get Identity of multiple insertion in sql server 2008

INSERT INTO TABLEB(Col1,Col2,Col3,Col4)
SELECT * FROM TABLEA WHERE Col1 is NULL AND Col2 is NULL AND Col3 is NULL;

Sounds like you need the output operator:
declare #TableA table(Col1 int, Col2 int, Col3 int, Col4 int);
declare #TableB table(id int identity(1,1), Col1 int, Col2 int, Col3 int, Col4 int);
declare #Audit table(id int);
insert into #TableA
select 1,3,7,null union all
select null, null, null, 45 union all
select null, null, null, 67;
-- copy null columns from #TableA to #TableB
-- and output id's to #Audit
insert into #TableB
output inserted.id
into #Audit
select *
from #TableA
where Col1 is null
and Col2 is null
and Col3 is null;
-- Copied #TableB values and #Audit values
select * from #TableB;
select * from #Audit;

Related

Insert into a table with the data present in one table which match the first row of another table

I am new to sql.
I want to insert a data to backup table from main table that also matches the first record of another table.
suppose I have backup table with name "baktble" and main table with name "sales".
note : both tables have same columns c1,c2,c3,c4,c5,c6.
and I have a buffer table "buftble" with columns only the first 3 columns of bakup and sales table c1,c2,c3.
Now how to insert a data into backup table from sales table which matches the columns of first record.
I tired this but got error.
insert into baktble
select *
from sales
where col1,col2,col3 in (
select top 1 col1,col2,col3
from buftble).
So while nbk's as is the correct SQL syntax for your query:
create table baktble(col1 int, col2 int, col3 int, col4 int, col5 int, col6 int);
create or replace table sales(col1 int, col2 int, col3 int, col4 int, col5 int, col6 int);
create or replace table buftble(col1 int, col2 int, col3 int);
insert into buftble values
(1,10,100),
(2,20,200),
(3,30,300);
insert into sales values
(1,10,100, 101, 102, 103),
(2,20,200, 201, 202, 203),
(3,30,300, 301, 302, 303);
insert into baktble
select *
from sales
where (col1,col2,col3) in (
select top 1 col1,col2,col3
from buftble);
this only ever inserts zero or one row from sales into baktble.
Because the top 1 only selects one row from buftble
If I had to guess what you are wanting to do is ether:
insert all sales that match the distinct rows in buftble
insert the first sales row that matches the distinct rows in buftble
The first is done with:
insert into baktble
select *
from sales
where (col1,col2,col3) in (
select distinct col1,col2,col3
from buftble);
and the later (with the assumption that col4 is valid to sort duplicate values by) using QUALIFY and ROW_NUMBER like so:
insert into baktble
select *
from sales
where (col1,col2,col3) in (
select distinct col1,col2,col3
from buftble)
qualify row_number() over (partition by col1,col2,col3 order by col4 desc) = 1;

How to select more columns than insert column

I have the following query:
INSERT INTO TableA (Col1, Col2, Col3)
OUTPUT #SomeData, INSERTED.ID, ID INTO TableB(SomeColumn, TableAID, ID)
SELECT Col1, Col2, Col3, ID
FROM TableC;
When I run it, I get this error:
The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
That error makes sense, but I don't know how to fix it. I want to select 4 columns from TableC, but I want to only insert three of them (Col1, Col2, Col3) into TableA. I am selecting the column ID because I want to insert it into the ID column of TableB. Is there any way to do that?
CREATE TABLE TableA
(
ID bigint identity
constraint PK_TableA_ID
primary key
Col1 int,
Col2 int,
Col3 int
)
CREATE TABLE TableB
(
ID [int] NOT NULL,
SomeColumn [int] NOT NULL,
TableAID [bigint] NOT NULL
);
CREATE TABLE TableC
(
ID [int] IDENTITY (1,1) NOT NULL,
Col1 [int],
Col2 [int],
Col3 [int],
);
You can try merge and write something like this:
MERGE TableA AS target
USING TableC AS source
ON 1 = 0
WHEN NOT MATCHED BY target
THEN INSERT (Col1, Col2, Col3) VALUES (source.Col1, source.Col2, source.Col3)
OUTPUT #SomeData, INSERTED.ID, source.ID INTO TableB (SomeColumn,TableAID, ID);

How to write a SQL query for the below?

I have two tables with n of columns from Col1 to Col30
Table 1.
Templateid Col1 Col2 Col3 Col4 ...
95 2019-05-28 1234 test123 123456
Table 2.
Templateid DisplayName ColumnName
95 date col1
95 rank col2
95 purpose col3
95 sign col4
Expected Results.
Col1Name Col1Value Col2Name Col2Value Col3Name Col3Value ....
date 2019-05-28 rank 1234 purpose test123
This is a crude way of doing it and if you do not know the number of columns in each table you would need to use dynamic sql to enumerate them out but for the purposes of this example I have assumed you do know the number of columns and the names you want to populate.
The union query allows you to pre-populate the desired column names using the col1 syntax, then the pivot allows you to match up the displaynames and the display values. A case statement is required to ensure the correct values are shown and you do need to populate your derived column names for the pivot query but you do get the desired outcome this way.
declare #table1 table (
Templateid int,
Col1 date,
col2 int,
col3 nvarchar(10),
col4 int
);
insert into #table1 (Templateid, col1, col2, col3, col4)
values
(95, '2019-05-28', '1234', 'test123', '123456');
declare #table2 table (
Templateid int,
Displayname nvarchar(10),
ColumnName nvarchar(10)
);
insert into #table2 (Templateid, Displayname, ColumnName)
values
(95, 'date', 'col1'),
(95, 'rank', 'col2'),
(95, 'purpose', 'col3'),
(95, 'sign', 'col4');
select * from
(
select columnname+'Name' as columnname, Displayname
from #table2 t2
union
select columnname+'Value', case when columnname='col1' then cast(col1 as nvarchar(15))
when columnname='col2' then cast(col2 as nvarchar(15))
when columnname='col3' then cast(col3 as nvarchar(15))
when columnname='col4' then cast(col4 as nvarchar(15)) end
from #table1 t1 inner join #table2 t2 on t1.Templateid=t2.Templateid) src
pivot
(max(displayname) for columnname in ([col1Name],[col1Value], [col2Name],[col2Value], [col3Name],[col3Value], [col4Name],[col4Value])) piv;

How to split 4 columns, one row into 2 columns, two rows?

I am using SSRS 2008R2 and SSMS 2008R2 and I am trying to split 4 columns, one row into two rows, 2 columns. How can I do this?
Here is some sample data:
create table #foo
(col1 int, col2 int, col3 int, col4 int)
insert #foo values(1,2,3,4)
insert #foo values(5,6,7,8)
insert #foo values(9,10,11,12)
select * from #foo
But I want to transform this data to look like this:
create table #goo (col1 int, col2 int)
insert #goo values(1,2)
insert #goo values(3,4)
insert #goo values(5,6)
insert #goo values(7,8)
insert #goo values(9,10)
insert #goo values(11,12)
select * from #goo
How can I do this?
As simple as:
create table #foo(col1 int, col2 int, col3 int, col4 int);
insert #foo values(1,2,3,4),(5,6,7,8),(9,10,11,12);
SELECT col1, col2
FROM #foo
UNION ALL
SELECT col3, col4
FROM #foo;
LiveDemo
First 2 columns UNION ALL with 3rd and 4th columns.
If you need to store in #goo use:
SELECT col1, col2
INTO #goo
FROM #foo
UNION ALL
SELECT col3, col4
FROM #foo;
SELECT * FROM #goo;
I imagine it would look something like this
SELECT CONCAT_WS(" ", col1, col2) FROM #foo UNION ALL
SELECT CONCAT_WS(" ", col3, col4) FROM #foo;
Breakdown
concat_ws - Combines two columns with a word separator. In this case a space.
Union All - Merges with another selector to create multiple rows.
SQLFiddle
http://sqlfiddle.com/#!9/ca24df/3/0

How to convert a column header and its value into row in sql?

I have a table with columns say col1, col2, col3. The table has many rows in it.
Let's assume val1, val2, val3 is one such row. I want to get the result as
Col1, Val1
Col2, Val2
Col3, Val3
That is 3 rows - one for each column and its value.
I am using SQL Server 2008. I read about pivots. Are pivots a way to solve this problem? Can someone route me to some examples or solutions how to solve this problem?
Thanks a lot
Maybe something like this:
Test data
DECLARE #T TABLE(Col1 INT, Col2 INT, Col3 INT)
INSERT INTO #T
VALUES (1,1,1)
Query
SELECT
*
FROM
(
SELECT
t.Col1,
t.Col2,
t.Col3
FROM
#T AS t
) AS SourceTable
UNPIVOT
(
Value FOR Col IN
(Col1,Col2,Col3)
) AS unpvt
Output
1 Col1
1 Col2
1 Col3
To do this kind of thing read the following: Using PIVOT and UNPIVOT
Pivot function allow you to convert row values in from of column..
Also check : Dynamic Pivoting in SQL Server
Example :
create table #temptable(colorname varchar(25),Hexa varchar(7),rgb varchar(1), rgbvalue tinyint)
GO
insert into #temptable values('Violet','#8B00FF','r',139);
insert into #temptable values('Violet','#8B00FF','g',0);
insert into #temptable values('Violet','#8B00FF','b',255);
insert into #temptable values('Indigo','#4B0082','r',75);
insert into #temptable values('Indigo','#4B0082','g',0);
insert into #temptable values('Indigo','#4B0082','b',130);
insert into #temptable values('Blue','#0000FF','r',0);
insert into #temptable values('Blue','#0000FF','g',0);
insert into #temptable values('Blue','#0000FF','b',255);
SELECT colorname,hexa,[r], [g], [b]
FROM
(SELECT colorname,hexa,rgb,rgbvalue
FROM #temptable) AS TableToBePivoted
PIVOT
(
sum(rgbvalue)
FOR rgb IN ([r], [g], [b])
) AS PivotedTable;
Create a temproary table:
CREATE TABLE #table2
(
name NCHAR,
bonus INT
)
Now Select and execute the below statement if there is an empty.
SELECT * FROM #table2
INSERT INTO #table2 (name,bonus) VALUES ('A',10)
INSERT INTO #table2 (name,bonus) VALUES ('B',20)
INSERT INTO #table2 (name,bonus) VALUES ('C',30)
After insert the values into table. select and execute the below line if you get records:
SELECT * FROM #table2
Input:
name bonus
A 10
B 20
C 30
Change the input into like this result
Result:
Cost A B C
Bonus 10 20 30
By using this code:
SELECT 'Bonus' AS Cost,
[A],[B],[C]
FROM
(SELECT name, Bonus
FROM #table2) AS TempTbl
PIVOT
(
AVG(bonus)
FOR [name] IN ([A],[B],[C])
) AS PivotTable;