Here's what I am trying to do.
This is the select statement
select Id
from tblUsersPokemons
where UserId = 1 and PokemonPlace = 'bag'
Now I want to insert those returned Ids into another table like this:
foreach all returned Ids
insert into tblNpcBattleUsersPokemons values (Id, 1)
How can I do that ?
Like this:
insert into tblNpcBattleUsersPokemons
select Id, 1 from tblUsersPokemons where UserId=1 and PokemonPlace='bag'
This can be done in a single sql call
insert into tblNpcBattleUsersPokemons (id, [whatever the name of the other column is])
select Id, 1 from tblUsersPokemons where UserId=1 and PokemonPlace='bag'
I've used the longhand here because it does not make any assumption about the ordering of columns in the destination table, which can change over time and invalidate your insert statement.
You can insert the set retrieved by a SELECT into another existing table using the INSERT...SELECT syntax.
For example:
INSERT INTO tblNpcBattleUsersPokemons (Id, Val) -- not sure what the second column name was
SELECT Id FROM tblUsersPokemons WHERE UserID = 1 and PokemonPlace='bag';
Related
Want to add a incremental number in MERGE when the NOT MATCHED case.
It only allows to write insert statements, I tried to set the value using the MAX() function too, but adds the same number to all the records.
What is expected
MERGE #targetTable AS [target]
USING #sourceTable AS [source] ON [target].key = [source].key
WHEN MATCHED
UPDATE ROWS
WHEN NOT MATCHED THEN
INSERT (id, Name)
VALUES ([incremented_id], source.Name);
Note : Table already have some records in it.
Any help would be appreciated
Try to get max ID from the table and then add it to this parameter. With this select you will be creating a new id of every row that is inserted. Something like this should work
declare #root int = 64895
WHEN MATCHED
UPDATE ROWS
WHEN NOT MATCHED THEN
INSERT (id, Name)
VALUES( ((#root - 1) + ROW_NUMBER() over(order by ID)), source.Name);
I have a table that has the following columns, and I cannot modify the schema (i.e. I can't modify the table or add an identity field).
What I want is to create a trigger to update one column to treat it as an identity field.
accountno firstname lastname keyField
jku45555 John Doe 123
Now what I want is when I insert the next record, I grab the KeyFieldId of the previous record and update the newly inserted record to be 124 (keep in mind this a Varchar field).
I need the best possible way of doing this, and like I said modifying the table is not an option. Thanks!
You want to do something like this... For a table named "Foo", with two columns, First Name and KeyFieldId (both varchar), this trigger will do what you want:
-------------------------------------------------------------------------
-- These lines will create a test table and test data
--DEBUG: CREATE TABLE Foo (FirstName varchar(20), KeyFieldId varchar(10))
--DEBUG: INSERT INTO Foo VALUES ('MyName', '145')
--
CREATE TRIGGER test_Trigger ON Foo
INSTEAD OF INSERT
AS
BEGIN
DECLARE #maxKeyFieldId int;
SELECT #maxKeyFieldId = MAX(CAST(KeyFieldId AS int)) FROM Foo;
WITH RowsToInsert AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY (CAST(KeyFieldId AS int))) AS RowNum
FROM inserted
) INSERT INTO Foo (FirstName, KeyFieldId)
SELECT FirstName, #maxKeyFieldId + RowNum
FROM RowsToInsert;
END
Things to note here:
Create an INSTEAD OF INSERT trigger
Find the "max" value of the INTEGER value of your KeyFieldID
Create a CTE that selects everything from the 'inserted' collection
Add a column to the CTE for a Row Number
Do the actual INSERT by adding row number to the max KeyFieldID
I have heard that the 'inserted' table automatically stores the last inserted record of any table temporarily.I was able to get the values from this inserted table when using triggers but not manually as
insert into samantha (id , name) values (11,'has')
select *from inserted
I am getting the error message as
Invalid object name 'inserted'.
Can you please give the reason.Thanks in advance
There is inserted table, but it can be only used with output clause, with something like this:
insert into samantha (id , name)
output inserted.*
values (11,'has')
If you have an identity field and you want the latest value from it, you can use SCOPE_IDENTITY() -function too:
insert into samantha (id , name)
values (11,'has')
select SCOPE_IDENTITY()
try use SELECT LAST_INSERT_ID() from samantha
I'm inserting into a table in MS SQL Server 2008 (it's rather a copy of values from the same table) and want to get the output values for the insert. I want to get the id value of the select statement (t.id in the example below), the INSERTED.id works just fine
create table tmp.tbl_inserted (fromId int, toId int)
INSERT INTO mytable (name)
OUTPUT t.id, INSERTED.id INTO tmp.tbl_inserted
SELECT t.name FROM mytable t
Thanks in advance
You can't do it directly from an INSERT:
from_table_name
Is a column prefix that specifies a table included in the FROM clause of a DELETE, UPDATE, or MERGE statement that is used to specify the rows to update or delete.
Note that INSERT isn't mentioned.
What you have to do instead is cheat and use a MERGE:
MERGE INTO mytable m
USING (name,id FROM mytable) t ON 1=0
WHEN NOT MATCHED THEN INSERT (name) VALUES (t.name)
OUTPUT t.id, INSERTED.id INTO tmp.SizeCurveGroup_inserted
;
I want to create a merge that will compare two tables and insert not matched values into another third table or table variable
something like this:
MERGE Assets AS target
USING (#id, #name)FROM Sales AS source (id, name) ON (target.id = SOURCE.id)
WHEN MATCHED THEN
UPDATE SET target.Status = #status, target.DateModified = SYSUTCDATETIME()
WHEN NOT MATCHED THEN
INSERT INTO #tableVar (id, name, status, dateModified)
VALUES (#id, #name, #status, SYSUTCDATETIME())
Can this be done or are there other methods?
You just cannot do this. MERGE operates on two tables only - source and target.
For your requirement, you need to e.g. use a CTE (Common Table Expression) to find the rows that don't match - and insert those into the third table.
Something like:
;WITH NonMatchedData AS
(
-- adapt this as needed - just determine which rows match your criteria,
-- and make sure to return all the columns necessary for the subsequent INSERT
SELECT (columns)
FROM dbo.SourceTable
WHERE ID NOT IN (SELECT DISTINCT ID FROM dbo.TargetTable)
)
INSERT INTO dbo.ThirdTable(Col1, Col2, ....., ColN)
SELECT Col1, Col2, ....., ColN
FROM NonMatchedData
You CAN do this very easily...
You can wrap the MERGE statement within a INSERT INTO FROM:
http://technet.microsoft.com/en-us/library/bb510625.aspx#sectionToggle2
-OR-
You can do it directly within the merge statement:
Quick example:
WHEN NOT MATCHED THEN
DELETE
OUTPUT Deleted.* INTO dbo.MyTable;
This will insert the non-matches into your existing destination table. You can use the Updated, Inserted, Deleted v-tables to direct data other places.