Select multi identity values for multiple inserts along with columns not inserted into the table - sql

I am inserting only 1 column into TempId table i.e name from a select statement
How do i get corresponding orderId for the identity column.
INSERT INTO tempId
output inserted.ID
Select name FROM (
select 'erty' as name, 1 as orderid union
select 'rth' as name, 2 as orderid union
select 'yt' as name, 3 as orderid union
select '345' as name, 4 as orderid union
select 'rtyu' as name, 5 as orderid union
select 'uio' as name, 6 as orderid union
select 'yu' as name, 7 as orderid union
select 'xzf' as name, 8 as orderid
) as a
PS Note: SELECT with union is only done for sample query. Ideally I will get things from another table.

You put the id and any other fields you need to use later in a table varaiable or temp table by using the OUTPUT clause
DECLARE #MyTableVar table( ID int, orderid int);
INSERT mytable (field1, orderID)
OUTPUT INSERTED.ID, INSERTED.OrderID
INTO #MyTableVar
SELECT FIELD2, orderid FROM Myothertable
Now you have the data available in #MyTableVar to do inserts to child tables or the other work you wanted to do.

just arrange the columns:
create table #tempID( id int, name varchar(50))
INSERT INTO #tempID (name, id)
output inserted.ID
Select name, orderid FROM (
select 'erty' as name, 1 as orderid union
select 'rth' as name, 2 as orderid union
select 'yt' as name, 3 as orderid union
select '345' as name, 4 as orderid union
select 'rtyu' as name, 5 as orderid union
select 'uio' as name, 6 as orderid union
select 'yu' as name, 7 as orderid union
select 'xzf' as name, 8 as orderid
) as a

This is an example on inserting values directly. If there are no triggers you can get ##IDENTITY.
insert into [FTSwordDef] ([word]) values ('value')
select scope_identity();
Scope_identity (and the evil ##) will only return the last iden. If you are inserting multiple rows then I think you would need to loop in a SP and build up the list of iden. Iden is created by the insert and is not available IN the insert to my knowledge.
If you held a tablock on the the insert and retrieved the last identity and how many rows were inserted then in theory the insert got the last x inden values. If your insert was sorted you would know what iden went with which row.

Related

Insert/join table on multiple conditions

I’ve a table that looks like this:
Table A
Version,id
5060586,22285
5074515,22701
5074515,22285
7242751,22701
7242751,22285
I want to generate a new key called groupId that is inserted as my example below:
Table A
Version,id,groupId
5060586,22285,1
5074515,22701,2
5074515,22285,2
7242751,22701,2
7242751,22285,2
I want the groupId to be the same as long as the id's are the same in the different versions. So for example version 5074515 and 7242751 has the same id's so therefor the groupId will be the same. If all the id's aren't the same a new groupId should be added as it has in version 5060586.
How can i solve this specific problem in SQL oracle?
One approach is to create a unique value representing the set of ids in each version, then assign a groupid to the unique values of that, then join back to the original data.
INSERT ALL
INTO t (version,id) VALUES (5060586,22285)
INTO t (version,id) VALUES (5074515,22701)
INTO t (version,id) VALUES (5074515,22285)
INTO t (version,id) VALUES (7242751,22701)
INTO t (version,id) VALUES (7242751,22285)
SELECT 1 FROM dual;
WITH groups
AS
(
SELECT version
, LISTAGG(id,',') WITHIN GROUP (ORDER BY id) AS group_text
FROM t
GROUP BY version
),
groupids
AS
(
SELECT group_text, ROW_NUMBER() OVER (ORDER BY group_text) AS groupid
FROM groups
GROUP BY group_text
)
SELECT t.*, groupids.groupid
FROM t
INNER JOIN groups ON t.version = groups.version
INNER JOIN groupids ON groups.group_text = groupids.group_text;
dbfiddle.uk
You can use:
UPDATE tableA t
SET group_id = ( SELECT COUNT(DISTINCT id)
FROM TableA x
WHERE x.Version <= t.version );
Which, for the sample data:
CREATE TABLE TableA (
Version NUMBER,
id NUMBER,
group_id NUMBER
);
INSERT INTO TableA (Version, id)
SELECT 5060586,22285 FROM DUAL UNION ALL
SELECT 5074515,22701 FROM DUAL UNION ALL
SELECT 5074515,22285 FROM DUAL UNION ALL
SELECT 7242751,22701 FROM DUAL UNION ALL
SELECT 7242751,22285 FROM DUAL;
Then, after the update:
SELECT * FROM tablea;
Outputs:
VERSION
ID
GROUP_ID
5060586
22285
1
5074515
22701
2
5074515
22285
2
7242751
22701
2
7242751
22285
2
db<>fiddle here

How to ROWCOUNT_BIG() value with union all

I have the following query in SQL Server. How do I get the number of rows of previous select query as following format?
Sample Query
select ID, Name FROM Branch
UNION ALL
SELECT ROWCOUNT_BIG(), ''
Sample Output
If you use a CTE you can count the rows and union all together:
with cte as (
select ID, [Name]
from dbo.Branch
)
select ID, [Name]
from cte
union all
select count(*) + 1, ''
from cte;
I think you want to see total count of the select statement. you can do this way.
CREATE TABLE #test (id int)
insert into #test(id)
SELECT 1
SELECT id from #test
union all
SELECT rowcount_big()
Note: Here, the ID will be implicitly converted to BIGINT datatype, based on the datatype precedence. Read more
Presumably, you are running this in some sort of application. So why not use ##ROWCOUNT?
select id, name
from . . .;
select ##rowcount_big; -- big if you want a bigint
I don't see value to including the value in the same query. However, if the underlying query is an aggregation query, there might be a way to do this using GROUPING SETS.
Here are two ways. It's better to use a CTE to define the row set so further table inserts don't interfere with the count. Since you're using ROWCOUNT_BIG() these queries use COUNT_BIG() (which also returns bigint) to count the inserted rows. In order to make sure the total always appears as the last row an 'order_num' column was added to the SELECT list and ORDER BY clause.
drop table if exists #tTest;
go
create table #tTest(
ID int not null,
[Name] varchar(10) not null);
insert into #tTest values
(115, 'Joe'),
(116, 'Jon'),
(117, 'Ron');
/* better to use a CTE to define the row set */
with t_cte as (
select *
from #tTest)
select 1 as order_num, ID, [Name]
from t_cte
union all
select 2 as order_num, count_big(*), ''
from t_cte
order by order_num, ID;
/* 2 separate queries could give inconsistent result if table is inserted into */
select 1 as order_num, ID, [Name]
from #tTest
union all
select 2 as order_num, count_big(*), ''
from #tTest
order by order_num, ID;
Both return
order_num ID Name
1 115 Joe
1 116 Jon
1 117 Ron
2 3

Insert new records with several ids from another table

I have a table, which has 9 records with id = 1 - 9 (for example, there can be more than 20 ids).
I have one varchar value = 'premium'.
I need to insert these values to another table, after this action I should have 9 records with id from the first table and 'premium' varchar in the second table:
1, 'premium';
2, 'premium';
etc.
How to write the function for SQL?
Are you looking for insert . . . select or create table as?
insert into table2 (id, value)
select id, 'premium'
from table1;
or:
create table table2 as
select id, 'premium' as value
from table1;
Do you want this?
demo:db<>fiddle
INSERT INTO second_table (id, text_value)
SELECT id, 'premium'
FROM first_table;

Inserting unique value from another table

Tables: I have 3 tables
They are cust, new_cust, old_cust
all of them have 3 columns, they are id, username, name
each of them have possibilities to have same data as the others.
I would like to make "whole" table that consisting all of them but only the uniques.
I've Tried
Creating a dummy table
I've tried to create the dummy table called "Temp" table by
select *
into Temp
from cust
insert all table to dummy
Then I insert all of them into they Temp table
insert into temp
select * from new_cust
insert into temp
select * from old_cust
taking uniques using distinct
After they all merged I'm using distinct to only take the unique id value
select distinct(id), username, fullname
into Whole
from temp
it did decreasing some rows
Result
But after I move it to whole table I would like to put primary key on id but I got the message that there are some duplicate values. Is there any other way?
I am guessing that you want unique ids. And you want these prioritized by the tables in some order. If so, you can do this with union all and row_number():
select id, username, name
from (select c.*,
row_number() over (partition by id order by priority) as seqnum
from ((select id, username, name, 1 as priority
from new_cust
) union all
(select id, username, name, 2 as priority
from cust
) union all
(select id, username, name, 3 as priority
from old_cust
)
) c
) c
where seqnum = 1;
Try this:
insert into temp
select * from new_cust
UNION
select * from old_cust
Union will avoid the duplicate entries and you can then create a primary key on ID column
Try this below query...
WITH cte as (
SELECT id, username, NAME,
ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY t1.username, t1.name ) AS rn
FROM cust t1
LEFT JOIN new_cust t2 ON t1.Id = t2.Id
LEFT JOIN old_cust t3 ON t2.Id = t3.Id
)
SELECT id, username, NAME
FROM cte
WHERE rn = 1
Note:-
Put all the query inside a CTE(Common table expression)
with a new column(rn) that you will use to filter the results.
This new Column will produce ROW_NUMBER()....PARTITION BY username,name.....
But after I move it to whole table I would like to put primary key on
id but I got the message that there are some duplicate values.?
That's because You are trying to insert ID value from each of the tables to Whole table.
Just insert username and name and skip ID. ID is IDENTITY and it MUST be unique.
Run this on Your current Whole table to see if You have duplicated Id's:
select COUNT(ID), username
from whole
GROUP BY username
HAVING COUNT(ID) > 1
To get unique customers recreate table Whole and make ID col IDENTITY:
IF OBJECT_ID ('dbo.Whole') IS NOT NULL DROP TABLE dbo.Whole;
CREATE TABLE Whole (ID INT NOT NULL IDENTITY(1,1), Name varchar(max), Username varchar(max))
Insert values into Whole table:
INSERT INTO Whole
SELECT Name, Username FROM cust
UNION
SELECT Name, Username FROM new_cust
UNION
SELECT Name, Username FROM old_cust
Make ID col PK.
What does Unique mean for your row ?
If it is only the username, and you don't care about keeping the old ID values,
this will favor the new_cust data over the old_cust data.
SELECT
ID = ROW_NUMBER() OVER (ORDER BY all_temp.username)
, all_temp.*
INTO dbo.Temp
FROM
(
SELECT nc.username, nc.[name] FROM new_cust AS nc
UNION
SELECT oc.username, oc.[name]
FROM old_cust AS oc
WHERE oc.username NOT IN (SELECT nc1.username FROM new_cust AS nc1) --remove the where part if needed
) AS all_temp
ALTER TABLE dbo.Temp ALTER COLUMN ID INTEGER NOT NULL
ALTER TABLE dbo.Temp ADD PRIMARY KEY (ID)
If by Unique you mean both the username and name then just remove the where part in the union

SQL Simple Join and I'm stumped

I have a table with columns:
JOB_NUM, HM_PH, BUS_PH, CALL1ST
Where the job_num is a unique number
And the HM_PH, BUS_PH, and CALL1ST columns are 10 digit phone numbers
So using the order of columns above, sample data would look like:
JOB_NUM, HM_PH, BUS_PH, CALL1ST
------------------------------------
12345, 4025557848, 9165897588, 7518884455
10101, 8887776655, 8667416895, 5558884446
What I want to produce is 2 columns.
JOB_NUM, PHONE
Where the job_num is listed next to every phone number such as:
JOB_NUM PHONE
---------------------
12345 4025557848
12345 9165897588
12345 7518884455
10101 8887776655
10101 8667416895
10101 5558884446
Where do I start?
You need a UNION (if you want to remove duplicate rows) or UNION ALL (if you want to keep duplicate rows):
SELECT JOB_NUM, HM_PH AS PHONE FROM yourtable
UNION
SELECT JOB_NUM, BUS_PH FROM yourtable
UNION
SELECT JOB_NUM, CALL1ST FROM yourtable
ORDER BY JOB_NUM
Make a UNION ALL for all numbers you need (with duplicates) or UNION when you need unique rows:
select JOB_NUM,HM_PH AS PHONE
from YourTableName
union all
select JOB_NUM,BUS_PH AS PHONE
from YourTableName
union all
select JOB_NUM,CALL1ST_PH AS PHONE
from YourTableName
create table yourtable
(
id int,
HM_PH nvarchar(10),
BUS_PH nvarchar(10),
CALL1ST nvarchar(10)
)
insert into yourtable
select 12345, 4025557848, 9165897588, 7518884455
union
select 10101, 8887776655, 8667416895, 5558884446
select * from yourtable
select ID,p.Phone
from temptemp
unpivot( Phone for phoneCol in (HM_PH,BUS_PH,CALL1ST)) p
order by id
drop table yourtable