473,437 Members | 1,728 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,437 software developers and data experts.

Multiple Inserts

Hello,

I want to do two sql INSERTS into the same table (table holds pk and fk rows) but I need the second insert to use the new Identity from the first INSERT. Something like:

Expand|Select|Wrap|Line Numbers
  1. INSERT INTO [table]
  2. SELECT [Cols] FROM [Table] Where [blah];SELECT NewUDValue AS @@IDENTITY;
  3. UNION ALL
  4. SELECT [colName = NewUDValue, more cols] FROM [Tablle] Where [Blah]
However this doesn't work! Is this even possible or will I need to split this into 2 seperate calls completly?

Thanks,
Steve
Aug 24 '10 #1

✓ answered by ck9663

Stevie,

I'm not sure it's possible for the identity value be available in a single atomic statement. The insert has to be completed first with no (syntax, constraint, etc) error before it becomes available. The reason is, SQL Server internally keeps track of the value of what you just inserted. That's why even if you rollback DML command, you will not be able to reuse the identity that's already been used. Because, internally, it's being monitored.

You're going to have to use a two statements T-SQL. If you need to rollback for any error, use transaction processing and reseed your identity as necessary.

Good Luck!!!

~~ CK

7 2269
NeoPa
32,556 Expert Mod 16PB
I have no idea what concept you're trying to explain with your example SQL (which just appears in so many ways) so I suggest you actually just ask the question in clear English. Always a good idea anyway to be fair.
Aug 24 '10 #2
Basically I want to insert two rows into the same table using one SQL call.

The second row to be inserted needs to use the newly created ID (auto generated primary key) from the first row. So I know that I can get the newly created ID from the first call using @@IDENTITY but can I use this in the second Insert statement? If I do 2 completly seperate calls to the database then it's fine but I want to do just one call.

Hope that makes sense...
Aug 24 '10 #3
NeoPa
32,556 Expert Mod 16PB
I don't think this can make sense as you describe it Steve.

I'm sort of guessing much as there is still much that has not been properly described or explained, but if you are appending a single pair (WHERE [blah] refers to a single source record) then it may work. If you are expecting WHERE [blah] to cover multiple records then this cannot possibly succeed as @@IDENTITY (or either of its equivalents) can only remember the last one used. By definition all previous ones are lost and then you get a whole bunch of records added with the same ID. Frankly, there is so little info to work from here I cannot even imagine what you're about, selecting a single record from a table then adding back two records to the same table with different, but undetermined values in whatever fields you may know about but haven't shared.
Aug 24 '10 #4
Oralloy
988 Expert 512MB
What it looks like is that StevieMars wants to insert two rows into his target table, the second of which refers to the auto-generated key of the first.

However, it's really difficult to be sure what problem he's really trying to solve.

Still, the solution that results likely won't be portable SQL. And there is value staying within the standard.

Stevie, can you please tell us what your basic problem is, and not ask about optimized code? Perhaps we can suggest an appropriate solution.
Aug 24 '10 #5
ck9663
2,878 Expert 2GB
Stevie,

I'm not sure it's possible for the identity value be available in a single atomic statement. The insert has to be completed first with no (syntax, constraint, etc) error before it becomes available. The reason is, SQL Server internally keeps track of the value of what you just inserted. That's why even if you rollback DML command, you will not be able to reuse the identity that's already been used. Because, internally, it's being monitored.

You're going to have to use a two statements T-SQL. If you need to rollback for any error, use transaction processing and reseed your identity as necessary.

Good Luck!!!

~~ CK
Aug 24 '10 #6
Jerry Winston
145 Expert 100+
@Steve

I'm hesitant to post this solution because the details of your requirement are so scant. Although SQL will allow you to create PK/FK constraints on the same table, be careful because you can get into some hairy situations if you're not cautious.

The simplest solution is to create an AFTER INSERT trigger. Of course you can't allow recursive triggers, but you can insert into the same table in the AFTER INSERT trigger with the values from the special inserted object.

Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE [dbo].[tbl_SelfRef](
  2.     [PK] [int] IDENTITY(1,1) NOT NULL,
  3.     [RowType] [char](2) NULL,
  4.     [FK] [int] NULL)
  5. --First entry must reference itself
  6. INSERT INTO [dbo].[tbl_SelfRef]
  7. VALUES ('PK',1)
  8.  
  9. CREATE TRIGGER [dbo].[AutoSetFK] 
  10.    ON  [dbo].[tbl_SelfRef] 
  11.    AFTER INSERT
  12. AS 
  13. BEGIN
  14.  
  15.     SET NOCOUNT ON;
  16.     INSERT INTO dbo.tbl_SelfRef
  17.     SELECT
  18.     'FK',PK
  19.         FROM inserted
  20.  
  21. END
  22.  
  23. INSERT INTO [dbo].[tbl_SelfRef]
  24. VALUES ('PK',1)
  25. INSERT INTO [dbo].[tbl_SelfRef]
  26. VALUES ('PK',2)
  27. INSERT INTO [dbo].[tbl_SelfRef]
  28. VALUES ('PK',2)
  29. INSERT INTO [dbo].[tbl_SelfRef]
  30. VALUES ('PK',4)
  31.  
  32.  
  33.  
So what happens? For every value you insert (a PK value) a correlated "FK" row is added to the table with a FK equal to the PK of the "PK" row you just inserted.
Aug 24 '10 #7
Sorry if my explanation was a bit vague.

@jerry Winston you are correct that rows can have a correlated "FK" row with the FK equal to that of the "PK" row inserted before. The scenario isn't applicable to all rows. Basically each row represents a module in my application and I need there to be a relationship between some modules (parent module and child module)

@Ck this was what I was looking for (whether I can get the @@IDENTITY in the same call as the next insert).

I'll try and explain better in future posts - thanks for your help

Steve
Aug 25 '10 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: baruch | last post by:
Hello all, I'm using PHP/mySQL couple :) to insert and delete some informations based on some criterium and I don't like to look at my code full of FOR and IF's. 1) Example: In a list of...
3
by: Oasis | last post by:
Hello, I'm new to c#. I have situation where I want to execute a number of insert statements that differ only in a few dynamic values. When I was a Java programmer, I would do this with a...
0
by: jtocci | last post by:
I'm having a big problem with CREATE RULE...ON INSERT...INSERT INTO...SELECT...FROM...WHERE when I want to INSERT several (20~50) records based on a single INSERT to a view. Either I get a 'too...
4
by: Jo | last post by:
Hi, In SQL Server I can batch many insert statements ie : Create one string that looks thus : szSQL = "insert into xxx (..., ..., ...) values (..., ..., ...)" szSQL += "insert into xxx (...,...
4
by: Steven Blair | last post by:
I am looking for some advice on the following problem: I am using a GridView and a SQLDataSource. The problem is based around a Room Booking app I am currently writing. When the user makes a...
5
by: Humble Geek | last post by:
Hi all. Quick and perhaps silly question, but... I am using Pg 7.3. I am writing a function using pgplsql. This function will perform multiple inserts. Let's say two of the inserts are as...
9
by: dan | last post by:
within a loop i am building a sql insert statement to run against my (programatically created) mdb. it works but it seems unreasonably SLOW! Sorry, dont have the code here but the jist is very...
0
by: dustwel | last post by:
I am currently trying to write a trigger that when an insert or update is made to a table, it inserts a copy of the row into a log table. It currently works when one row is inserted, but it will...
2
gchq
by: gchq | last post by:
Hi there This was the closest to Sybase I could see.... If I wanted to perform a multiple insert based on values in a table using, say a web app, I'd define a DataTable and bring in the...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.