how to insert more than one record to sql table code example

Example 1: how to insert multiple records at once in sql acess

INSERT INTO target_table ( column_name1, column_name2 )
SELECT column_name1, column_name2
FROM (SELECT tableNameColumn AS column_name1, tableNameColumn2 FROM tableName, tableName2
WHERE tableNameColumn = 3 AND tableNameColumn2 = 1 
UNION ALL
SELECT tableNameColumn AS column_name1, tableNameColumn2 FROM tableName, tableName2
WHERE tableNameColumn = 3 AND tableNameColumn2 = 1) AS TMP

example:
INSERT INTO ProgKnowledge ( UserID, ProgramID )
SELECT UserID, ProgramID
FROM (SELECT Users.ID AS UserID, Programs.ProgramID FROM Users, Programs
WHERE Programs.ProgramID = 3 AND Users.ID = 1
UNION ALL
SELECT Users.ID AS UserID, Programs.ProgramID FROM Users, Programs
WHERE Programs.ProgramID = 4 AND Users.ID = 1)  AS add;

Example 2: insert more than 1000 rows sql

BEGIN TRY
BEGIN TRANSACTION
-- Please enter 1000 rows for each insert
INSERT INTO OFBC_MD20_CC_Values (Column1, Column2, Column3, Column4, Column5, Cloumn6, Column7)
values('data1','data2','data3','data4','data5','data6','data7'),('data1','data2','data3','data4','data5','data6','data7')...   -- Till max 1000 rows
INSERT INTO OFBC_MD20_CC_Values (Column1, Column2, Column3, Column4, Column5, Cloumn6, Column7)
values('data1','data2','data3','data4','data5','data6','data7'),('data1','data2','data3','data4','data5','data6','data7')...... -- Till max 1000
INSERT INTO OFta3','data4','data5','data6','dBC_MD20_CC_Values (Column1, Column2, Column3, Column4, Column5, Cloumn6, Column7)
values('data1','data2','daata7'),('data1','data2','data3','data4','data5','data6','data7')...... -- Till max 1000
......Many time as needed

 

COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN -- RollBack in case of Error

DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY();

 

-- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
THROW 51000, @ErrorMessage, 1
END CATCH

Tags:

Sql Example