Select the rows that just inserted - sql

How can I retrieve the row just inserted?
INSERT INTO LETTRE_VOIT
select rsVoit.NOID, NO_ORDRE, rsOrdre.CODE_DEST, rsOrdre.MODAL_MODE, rsOrdre.MODAL_PORT,
CASE rsOrdre.MODAL_PORT
WHEN 'false' THEN 'D'
ELSE 'P'
END,
rsOrdre.LIVRS_EXPRS,
CASE rsOrdre.LIVRS_EXPRS
WHEN 'false' THEN 'L'
ELSE 'E'
END,
rsOrdre.ENLEV_UNITE, LIBELLE, NBR_COLIS,POID,ENLEV_CREMB,ENLEV_DECL
from ORDRE rsOrdre
inner join
(
select CODE_DEST,MODAL_MODE, MODAL_PORT, LIVRS_EXPRS,ENLEV_UNITE, ROW_NUMBER() over (order by CODE_DEST) as NOID
from ORDRE
group by CODE_DEST,MODAL_MODE,MODAL_PORT,LIVRS_EXPRS,ENLEV_UNITE
) rsVoit on rsVoit.CODE_DEST = rsOrdre.CODE_DEST and rsVoit.MODAL_MODE = rsOrdre.MODAL_MODE
and rsVoit.MODAL_PORT = rsOrdre.MODAL_PORT and rsVoit.LIVRS_EXPRS = rsOrdre.LIVRS_EXPRS
and rsVoit.ENLEV_UNITE = rsOrdre.ENLEV_UNITE
LEFT JOIN T_UNITE ON rsOrdre.ENLEV_UNITE = T_UNITE.NOID
WHERE (STATUT_ORDRE = 3) AND IS_PRINT = 'false' AND (TRANSPORTEUR IN (SELECT ParsedString From dbo.ParseStringList(#Trans)))
order by rsVoit.NOID, NO_ORDRE
SELECT * FROM LETTRE_VOIT WHERE ???
For example:
I inserted 2, it return 2
and then I inserted 3, I want return 3 instead of 5 rows.
Thanks in advance.
Stev
PS: May be I need to use a stored procedure ?

I'm not 100% sure what exactly you want back.... but SQL Server has an OUTPUT clause that can output stuff from INSERT and UPDATE and DELETE statements:
INSERT INTO dbo.YourTable(col1, col2, ..., colN)
OUTPUT Inserted.Col1, Inserted.IDCol, Inserted.Col17
VALUES(val1, val2, ...., valN)
Here, you're inserting values and the inserted values for the IDCol (e.g. an INT IDENTITY column), Col1 and Col17.
If just getting back the results into your grid in Mgmt Studio is good enough - then use the OUTPUT clause! Read more about the OUTPUT clause on Books Online

If you are using SQL Server
And you know how many row inserted then go through
SELECT top 2 * FROM LETTRE_VOIT order by primaryKeyId desc
put the number of row inserted at place of 2.
It may be help you, If you know the number of inserted rows, and then you can provide the numbers with top keyword

How about saving the records in a variable before inserting them or adding a date field and retrieve them by date?

Related

Conditional insert in SQL for an order system

I have a question regarding a conditional insert.
I want to be able to add the same ID in the ("tafelID" = tableID) column, ONLY if the ("betaalstatus" = pay status) is equal to true. What query do i have to use ?
I'm new to SQL. my query is below.
INSERT INTO Rekening (tafelID, betaalstatus) Select ('7', 'False')
WHERE not exists ( select 'False' )
you can replace "<...>" with the data in the nested select statement in FROM clause. you can use nested Case When statement for complex conditions.
INSERT INTO Rekening (tafelID, betaalstatus)
Select Case WHEN betaalstatus = true THEN tableID ELSE tafelID END tafelID, betaalstatus
FROM (SELECT <betaalstatus> AS betaalstatus, <tableID> AS tableID, <tafelID> AS tafelID)
-- i.e. (SELECT true AS betaalstatus, 7 AS tableID, 8 AS tafelID)

Oracle SQL Insert whit Case Select

I'm new in this site and I have another question. In this case, it is from Oracle SQL, Insert operation with a CASE.
My SQL insert's code is:
INSERT WHEN (SELECT TB0083_DS_TIPODISPOSITIVO FROM TB0083_TIPODISPOSITIVO WHERE TB0083_ID_TIPODISPOSITIVO = (SELECT FOR_DISPOSITIVO FROM TFORPD01 WHERE FOR_CODIGO = &FORNECEDOR))='TIV' THEN
INTO TTRAPD01 (TRA_CODIGO,TRA_CODBARRA,TRA_CODLOC,TRA_CODCON,TRA_DATLOC,TRA_CODCAIXA,TRA_STATCOND,TRA_DT_CRIACAO,TRA_NM_USUARIOCRIACAO,TRA_DT_ALTERACAO,TRA_NM_USUARIOALTERACAO,TRA_CD_CONTA,TRA_CODCTR,TRA_TRANSACAO_ONLINE,TRA_TIV_HEXA,TRA_TIV_BINARIO,TRA_CD_DISPOSITIVO,TRA_DATSINC,TRA_ID_TPSEGREG,TRA_FORNECEDOR,TRA_STATUS)
VALUES (&NUMEROIDENTIFICADOR,&CODIGOBARRAIDENTIFICADOR,&CODIGOPONTOVENDALARM,259,SYSDATE,&CODIGOCAIXA,0,SYSDATE,&USUARIOLOGUEADO,SYSDATE,&USUARIOLOGUEADO,422,1,0,&TIVHEXA,&TIVBINARIO,423,SYSDATE,3,&FORNECEDOR,1)
ELSE
INTO TTRAPD01 (TRA_CODIGO,TRA_CODBARRA,TRA_CODLOC,TRA_CODCON,TRA_DATLOC,TRA_CODCAIXA,TRA_STATCOND,TRA_DT_CRIACAO,TRA_NM_USUARIOCRIACAO,TRA_DT_ALTERACAO,TRA_NM_USUARIOALTERACAO,TRA_CD_CONTA,TRA_CODCTR,TRA_TRANSACAO_ONLINE,TRA_TIV_HEXA,TRA_TIV_BINARIO,TRA_CD_DISPOSITIVO,TRA_DATSINC,TRA_ID_TPSEGREG,TRA_FORNECEDOR,TRA_STATUS)
VALUES (&NUMEROIDENTIFICADOR,&CODIGOBARRAIDENTIFICADOR,&CODIGOPONTOVENDALARM,259,SYSDATE,&CODIGOCAIXA,0,SYSDATE,&USUARIOLOGUEADO,SYSDATE,&USUARIOLOGUEADO,422,1,0,&TIVHEXA,&TIVBINARIO,423,SYSDATE,2,&FORNECEDOR,1);
This script doesn't found.
I need to fix it, because I need to change the value of field TRA_ID_TPSEGREG depends on the value of:
SELECT TB0083_DS_TIPODISPOSITIVO FROM TB0083_TIPODISPOSITIVO WHERE TB0083_ID_TIPODISPOSITIVO = (SELECT FOR_DISPOSITIVO FROM TFORPD01 WHERE FOR_CODIGO = &FORNECEDOR)
If value is 'TIV' then it inserts 3 in that position, else it inserts 2 in those field.
Thanks!!
There's PL/SQL INSERT WHEN command:
Try this:
INSERT FIRST
WHEN TB0083_DS_TIPODISPOSITIVO = 'TIV' THEN
INTO TTRAPD01
(
<COLUMN_NAME1>,<COLUMN_NAME2>......
)
VALUES
(
<COLUMN_VALUE1>,<COLUMN_VALUE2>.....
)
ELSE
INTO TTRAPD01
(
<COLUMN_NAME1>,<COLUMN_NAME2>......
)
VALUES
(
<COLUMN_VALUE1>,<COLUMN_VALUE2>.....
)
SELECT TB0083_DS_TIPODISPOSITIVO
FROM TB0083_TIPODISPOSITIVO
WHERE TB0083_ID_TIPODISPOSITIVO =
(SELECT FOR_DISPOSITIVO FROM TFORPD01 WHERE FOR_CODIGO = &FORNECEDOR
);
For eg:
CREATE TABLE TEST ( ID NUMBER);
INSERT FIRST
WHEN dummy = 'Y' THEN
INTO TEST
VALUES(222)
ELSE
INTO TEST
VALUES(555)
select dummy from dual;
The above query will insert 1 ROW on the very first condition satisfy. See more: >>here<<

Converting Select and Update into Update with SubSelect in DB2

I have a select query as below:
SELECT COL1, COL2, COL3
FROM
(
SELECT A.COL1, B.COL2, A.COL3
FROM
SCHEMA1.TAB1 A, SCHEMA2.TAB2 B
WHERE
A.SOMECOL = B.SOMECOL
) TEMP
WHERE NOT EXISTS
(
SELECT 1 FROM SCHEMA3.TAB3 C WHERE C.COL3 = TEMP.COL3
)
Now in my current code setup, I am running the SELECT first to get the results and then in the next step, I am updating table SCHEMA3.TAB3 with below update query by iterating through the result set:
UPDATE SCHEMA3.TAB3 SET COL1=?, COL2=? WHERE COL3=?
Where the three parameter values are coming from the result of above SELECT.
But, now I want to convert this two steps of selecting and updating into a single update statement with a sub select and do away completely with parameter setting.
How can I do it ?
Something seems to be wrong with your question.
You are updating where TAB3.COL3 = TAB1.COL3, but in the original SELECT to obtain the values you have eliminated the rows where TAB3.COL3 = TAB1.COL3.

Yield Return equivalent in SQL Server

I am writing down a view in SQL server (DWH) and the use case pseudo code is:
-- Do some calculation and generate #Temp1
-- ... contains other selects
-- Select statement 1
SELECT * FROM Foo
JOIN #Temp1 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1
-- Do some calculation and generate #Temp2
-- ... contains other selects
-- Select statement 2
SELECT * FROM Foo
JOIN #Temp2 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1
The result of the view should be:
Select Statement 1
UNION
Select Statement 2
The intended behavior is the same as the yield returnin C#. Is there a way to tell the view which SELECT statements are actually part of the result and which are not? since the small calculations preceding what I need also contain selects.
Thank you!
Yield return in C# returns rows one at a time as they appear in some underlying function. This concept does not exist in SQL statements. SQl is set-based, returning the entire result set, conceptually as a unit. (That said, sometimes queries run slowly and you will see rows returned slowly or in batches.)
You can control the number of rows being returns using TOP (in SQL Server). You can select particular rows to be returned using WHERE statements. However, you cannot specify a UNION statement that conditionally returns rows from some components but not others.
The closest you may be able to come is something like:
if UseTable1Only = 'Y'
select *
from Table1
else if UseTable2Only = 'Y'
select *
from Table2
else
select *
from table1
union
select *
from table2
You can do something similar using dynamic SQL, by constructing the statement as a string and then executing it.
I found a better work around. It might be helpful for someone else. It is actually to include all the calculation inside WITH statements instead of doing them in the view core:
WITH Temp1 (ID)
AS
(
-- Do some calculation and generate #Temp1
-- ... contains other selects
)
, Temp2 (ID)
AS
(
-- Do some calculation and generate #Temp2
-- ... contains other selects
)
-- Select statement 1
SELECT * FROM Foo
JOIN Temp1 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1
UNION
-- Select statement 2
SELECT * FROM Foo
JOIN Temp2 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1
The result will be of course the UNION of all the outiside SELECT statements.

return a default record from a sql query

I have a sql query that I run against a sql server database eg.
SELECT * FROM MyTable WHERE Id = 2
This may return a number of records or may return none. If it returns none, I would like to alter my sql query to return a default record, is this possible and if so, how? If records are returned, the default record should not be returned. I cannot update the data so will need to alter the sql query for this.
Another way (you would get an empty initial rowset returned);
SELECT * FROM MyTable WHERE Id = 2
IF (##ROWCOUNT = 0)
SELECT ...
SELECT TOP 1 * FROM (
SELECT ID,1 as Flag FROM MyTable WHERE Id = 2
UNION ALL
SELECT 1,2
) qry
ORDER BY qry.Flag ASC
You can have a look to this post. It is similar to what you are asking
Return a value if no rows are found SQL
I hope that it can guide you to the correct path.
if not exists (SELECT top 1 * FROM mytable WHERE id = 2)
select * from mytable where id= 'whatever_the_default_id_is'
else
select * from mytable where id = 2
If you have to return whole rows of data (and not just a single column) and you have to create a single SQL query then do this:
Left join actual table to defaults single-row table
select
coalesce(a.col1, d.col1) as col1,
coalesce(a.col2, d.col2) as col2,
...
from (
-- your defaults record
select
default1 as col1,
default2 as col2,
...) as d
left join actual as a
on ((1 = 1) /* or any actual table "where" conditions */)
The query need to return the same number of fields, so you shouldn't do a SELECT * FROM but a SELECT value FROM if you want to return a default value.
With that in mind
SELECT value FROM MyTable WHERE Id = 2
UNION
SELECT CASE (SELECT count(*) FROM MyTable WHERE Id = 2)
WHEN 0 THEN 'defaultvalue'
END