code_junkie

SQL Server: Is it possible to insert into two tables at the same time?

Nov 11th, 2011
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. BEGIN TRANSACTION
  2. DECLARE @DataID int
  3. INSERT INTO DataTable (Column1 ...) VALUES (....)
  4. SELECT @DataID = scope_identity()
  5. INSERT INTO LinkTable VALUES (@ObjectID, @DataID)
  6. COMMIT
  7.  
  8. DECLARE @Object_Table TABLE
  9. (
  10. Id INT NOT NULL PRIMARY KEY
  11. )
  12.  
  13. DECLARE @Link_Table TABLE
  14. (
  15. ObjectId INT NOT NULL,
  16. DataId INT NOT NULL
  17. )
  18.  
  19. DECLARE @Data_Table TABLE
  20. (
  21. Id INT NOT NULL Identity(1,1),
  22. Data VARCHAR(50) NOT NULL
  23. )
  24.  
  25. -- create two objects '1' and '2'
  26. INSERT INTO @Object_Table (Id) VALUES (1)
  27. INSERT INTO @Object_Table (Id) VALUES (2)
  28.  
  29. -- create some data
  30. INSERT INTO @Data_Table (Data) VALUES ('Data One')
  31. INSERT INTO @Data_Table (Data) VALUES ('Data Two')
  32.  
  33. -- link all data to first object
  34. INSERT INTO @Link_Table (ObjectId, DataId)
  35. SELECT Objects.Id, Data.Id
  36. FROM @Object_Table AS Objects, @Data_Table AS Data
  37. WHERE Objects.Id = 1
  38.  
  39. -- now I want to copy the data from from object 1 to object 2 without looping
  40. INSERT INTO @Data_Table (Data)
  41. OUTPUT 2, INSERTED.Id INTO @Link_Table (ObjectId, DataId)
  42. SELECT Data.Data
  43. FROM @Data_Table AS Data INNER JOIN @Link_Table AS Link ON Data.Id = Link.DataId
  44. INNER JOIN @Object_Table AS Objects ON Link.ObjectId = Objects.Id
  45. WHERE Objects.Id = 1
  46.  
  47. $qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
  48.  
  49. $result = @mysql_query($qry);
  50.  
  51. $qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
  52.  
  53. $result = @mysql_query($qry2);
  54.  
  55. $qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
  56.  
  57.  
  58. $result = @mysql_query($qry);
  59.  
  60. $qry2 = "INSERT INTO table2 (two) VALUES('$two')";
  61.  
  62. $result = @mysql_query($qry2);
  63.  
  64. "$qry"-number and number in @mysql_query($qry"")
Add Comment
Please, Sign In to add comment