How can I get the computed column value as an output after SQL insert? [duplicate] - sql

This question already has answers here:
Get SQL Computed Column Inserted Value
(3 answers)
Closed 1 year ago.
I have a table definition like this:
ID int /* identity column */
SecondID nvarchar(50) /* ComputedColumn */
birthdate datet */ Simple Column */
I would like to insert values on this table and I would like to get the inserted value as output,
the first ID, I got it using the scope_identity function.
Computed Function : ID * 1000
as an example, I would like to insert these values : (1,1000,12/08/2021)
What can I get from now is only the ID,
CREATE PROCEDURE [dbo].[USER_insert]
#birthdate date,
#SecondIDOut nvarchar(50) output
Begin
AS
INSERT INTO [dbo].[User]
([birthdate])
VALUES
(#birthdate)
SET #ID = scope_identity()
/* SET #SecondIDOut = ?? what can I set here */
END
How can I get the SecondID after executing the SQL insert statement?

Use an OUTPUT clause:
DECLARE #vals TABLE (id int, secondid varchar(30));
INSERT INTO [dbo].[User] ([birthdate])
OUTPUT inserted.id, inserted.secondid INTO #vals;
VALUES
(#birthdate)
SELECT *
FROM #vals;
The last statement is just for example. You can assign the values to parameters if you prefer.

Related

Using OUTPUT INTO with from_table_name in an INSERT statement [duplicate]

This question already has answers here:
Is it possible to for SQL Output clause to return a column not being inserted?
(2 answers)
Closed 2 years ago.
Microsoft's OUTPUT Clause documentation says that you are allowed to use from_table_name in the OUTPUT clause's column name.
There are two examples of this:
Using OUTPUT INTO with from_table_name in an UPDATE statement
Using OUTPUT INTO with from_table_name in a DELETE statement
Is it possible to also use it in an INSERT statement?
INSERT INTO T ( [Name] )
OUTPUT S.Code, inserted.Id INTO #TMP -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
Failing example using table variables
-- A table to insert into.
DECLARE #Item TABLE (
[Id] [int] IDENTITY(1,1),
[Name] varchar(100)
);
-- A table variable to store inserted Ids and related Codes
DECLARE #T TABLE (
Code varchar(10),
ItemId int
);
-- Insert some new items
WITH S ([Name], Code) AS (
SELECT 'First', 'foo'
UNION ALL SELECT 'Second', 'bar'
-- Etc.
)
INSERT INTO #Item ( [Name] )
OUTPUT S.Code, inserted.Id INTO #T -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
No, because an INSERT doesn't have a FROM; it has a set of values that are prepared either by the VALUES keyword, or from a query (and even though that query has a FROM, you should conceive that it's already been run and turned into a block of values by the time the insert is done; there is no s.code any more)
If you want to output something from the table that drove the insert you'll need to use a merge statement that never matches any records (so it's only inserting) instead, or perhaps insert all your data into #tmp and then insert from #tmp into the real table - #tmp will thus still be the record of rows that were inserted, it's just that it was created to drive the insert rather than as a consequence of it (caveats that it wouldn't contain calculated columns)

How do i INSERT/UPDATE a table varieble from a SELECT query from another table in the database?

I am trying to insert/update a select query results to a table variable in sql-server stored procedure but for some reason only the first value is being updated
declare #student table(regdno int,semester_marks float null,temp float null);
insert into #student(regdno )
select regdno
from sem_marks
where allocId =#allocid
order by regdno asc;
AND
update #student
set regdno = sem_marks.regdno
from sem_marks
where sem_marks .allocId =#allocid ;
declare #student table(regdno int,semester_marks float ,temp float );
declared the table variable
need to insert the values of regdno from another table sem_marks into #student leaving columns semester_marks and temp blank currently which will be updated later on the the code
You just need to add the fields. Start with reading the documentation if you get stuck...
Here's a perfect example for your insert:
https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql?view=sql-server-2017#l-inserting-data-into-a-table-variable
https://learn.microsoft.com/en-us/sql/t-sql/queries/update-transact-sql?view=sql-server-2017

Select row just inserted without using IDENTITY column in SQL Server 2012

I have a bigint PK column which is NOT an identity column, because I create the number in a function using different numbers. Anyway, I am trying to save this bigint number in a parameter #InvID, then use this parameter later in the procedure.
ScopeIdentity() is not working for me, it saved Null to #InvID, I think because the column is not an identity column. Is there anyway to select the record that was just inserted by the procedure without adding an extra ID column to the table?
It would save me a lot of effort and work if there is a direct way to select this record and not adding an id column.
insert into Lab_Invoice(iID, iDate, iTotal, iIsPaid, iSource, iCreator, iShiftID, iBalanceAfter, iFileNo, iType)
values (dbo.Get_RI_ID('True'), GETDATE(),
(select FilePrice from LabSettings), 'False', #source, #user, #shiftID, #b, #fid, 'Open File Invoice');
set #invID = CAST(scope_identity() AS bigint);
P.S. dbo.Get_RI_ID('True') a function returns a bigint.
Why don't you use?
set #invId=dbo.Get_RI_ID('True');
insert into Lab_Invoice(iID,iDate,iTotal,iIsPaid,iSource,iCreator,iShiftID,iBalanceAfter,iFileNo,iType)
values(#invId,GETDATE(),(select FilePrice from LabSettings),'False',#source,#user,#shiftID,#b,#fid,'Open File Invoice');
You already know that big id value. Get it before your insert statement then use it later.
one way to get inserted statement value..it is not clear which value you are trying to get,so created some example with dummy data
create table #test
(
id int
)
declare #id table
(
id int
)
insert into #test
output inserted.id into #id
select 1
select #invID=id from #id

SQL Merge Statement - Output into a scalar variable (SQL Server)

I'm getting my head around the MERGE statement in SQL server. I generally use it to insert/update a single row, which I realise isn't the only use, but it's something I seem to do quite often.
But what happens if you want to insert a value of 1, or update to increment the value and output the incremented value eg:
CREATE TABLE [Counter] (
[Key] VARCHAR(255) NOT NULL PRIMARY KEY,
[Value] INT NOT NULL
);
DECLARE #paramKey VARCHAR(255);
SET #paramKey = 'String';
MERGE [Counter] AS targt
USING (Values(#paramKey)) AS source ([Key])
ON (targt.[Key] = source.[Key])
WHEN MATCHED THEN
UPDATE SET Value = Value +1
WHEN NOT MATCHED THEN
INSERT ([Key], Value)
VALUES (source.[Key], 1);
-- but now I want the new value!
Is there a way of doing this? I notice the output clause in https://msdn.microsoft.com/en-gb/library/bb510625.aspx but it doesn't seem to work with scalars (I could output to a single row-ed table variable but that seems wrong):
-- using table variables but seems
DECLARE #paramKey VARCHAR(255), #value int;
SET #paramKey = 'String'
DECLARE #Tab table (
[Value] INT
)
MERGE Counter AS targt
USING (Values(#paramKey)) AS source ([Key])
ON (targt.[Key] = source.[Key])
WHEN MATCHED THEN
UPDATE SET Value = Value +1
WHEN NOT MATCHED THEN
INSERT ([Key], Value)
VALUES (source.[Key], 1)
OUTPUT inserted.[Value] INTO #Tab;
-- can now use #Tab as a single rowed table variable
Is there a better option?

SELECT [...] WHERE X IN #variable [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parameterizing an SQL IN clause?
I have read-only access to a database which I'd like to do the following on:
DECLARE #var AS INT_COLLECTION = (1,2,3)
SELECT name,column
FROM table
WHERE column IN #var
Of course INT_COLLECTION doesn't exist, but is there something similar available in SQL Server 2008? Or another way to do this without write access to the database?
This is a pretty heavy-handed approach since you have to create a user-defined table type, but it does work:
CREATE TYPE INT_COLLECTION AS TABLE (
Value Int
);
GO
DECLARE #var AS INT_COLLECTION;
INSERT INTO #var (Value)
VALUES (1), (2), (3);
SELECT name, col
FROM YourTable
WHERE col IN (SELECT Value FROM #var)
You could do something like this:
DECLARE #var AS TABLE (IDS INT);
INSERT INTO #var VALUES (1),(2),(3);
SELECT name,column
FROM table
WHERE column IN ( SELECT IDS FROM #var)