How to insert multiple data into mssql without using loop?
i’m developing a clinic management system, while doctor may give few medicines to patient,therefore i hope inside my database,the data will look like
|-----------------------------------|
| RecordID | ItemID | Amount|
|-----------------------------------|
| 1 | 1 | 10 |
| 1 | 2 | 100 |
--------------------------------------
and now what i get is…
|-----------------------------------|
| RecordID | ItemID | Amount|
|-----------------------------------|
| 1 | 1 | 10 |
| 2 | 2 | 100 |
--------------------------------------
because i’m using store procedure and needed loop to store all “ItemID” into sql.
+------------+ +-----------------+
| record | | record_items |
+------------+ +-----------------+
|RecordID(PK)| > | RecordID (FK) |
|PatientID | | ItemID |
|Precription | | Amount |
|VisitDate | +-----------------+
+------------+
this is my 2 tables, i hope when storing data ,the recordID will not increase based on how many ItemID inserted.
ALTER PROCEDURE [dbo].[InsertPatientRecord]
-- Add the parameters for the stored procedure here
@PatientID INT,
@Prescription VARCHAR(50),
@VisitDate DATETIME,
@ItemID INT,
@Amount INT
AS
SET NOCOUNT On
DECLARE @RecordID INT
INSERT INTO record VALUES(@PatientID,@Prescription,@VisitDate)
SET @RecordID=Scope_Identity()
INSERT INTO record_item VALUES(@RecordID,@ItemID,@Amount)
RETURN
this is my stored procedure
Since you will potentially have multiple
record_itemsfor eachrecord, you need to have two stored procedures: one to writerecord(once) and one to write each of therecord_itemsassociated with the record.In order to make this work correctly, after writing
recordyou will need to retrieve therecordidso that it can be passed to the stored procedure forrecord_items.Here is a rough outline for the stored procedures; the rest of the work I’ll leave up to you.
One note: the RecordId is returned to the caller since it is an output parameter. This means that you will need to execute this procedure using a command (which you should be doing anyway) and will need to retrieve that value of this parameter after the stored procedure has been executed.
Here is the
recordsp:and here is the
record_itemssp: