Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, experts,
I am using SQL Server 2008.
If I want to insert a row in a table, then I simply use the following query
SQL
insert into Table1 (Col1, Col2) values  ('EDJ','LP')


And if I wanna check before inserting then I follow
SQL
If not exists (select 1 from Table1 where Col1='EDJ' and  Col2='LP) 
begin 
insert into Table1 (Col1, Col2) values  ('EDJ','LP') 
end 
else 
begin 
Print 'Data already exist.' 
end


Now, for multirow inserting in a single query, I follow
SQL
insert into Table1 (Col1, Col2) values  ('EDJ', 'LP'), ('AGE', 'LP'), ('DJR', 'VG')

But if I wanna check for multirow insertion in a single batch, then what would be the query ???

Thanks in advance.
Posted

1. Insert the value in a table variable first.
2. Check the existence.
3. Insert or show message.

SQL
DECLARE @TmpTbl TABLE (Col1 VARCHAR(100), col2 VARCHAR(100))

INSERT INTO @TmpTbl(Col1,Col2)VALUES('EDJ','LP'), ('AGE', 'LP'), ('DJR', 'VG')
  
  IF NOT EXISTS(
         SELECT 1
         FROM   Table1 t1
                INNER JOIN @TmpTbl t2
                     ON  t.Col1 = t2.Col1
                     AND t1.Col2 = t2.Col2
     )
  BEGIN
      INSERT INTO Table1(Col1,Col2)
      SELECT Col1,Col2
      FROM   @TmpTbl tt
  END
  ELSE
  BEGIN
      PRINT 'Data already exist.'
  END   
 
Share this answer
 
My suggestion is you can explore tsql Merge statement if it is sql server specific problem.
Code sample
SQL
CREATE TABLE Target(FirstName varchar(10), LastName varchar(10));
GO

CREATE TABLE #Source(FirstName varchar(10), LastName varchar(10));
INSERT INTO #Source(FirstName, LastName) VALUES('A','B'), ('C','D'), ('E','F');

Merge [Target] AS T
Using (SELECT * FROM #Source) AS S
ON (T.FirstName = S.FirstName AND T.LastName = S.LastName)
WHEN NOT MATCHED BY Target THEN
	INSERT (FirstName, LastName) VALUES(S.FirstName, S.LastName);
--If you want to do something like insert/update/delete then you can use following statement
--WHEN MATCHED THEN
  --UPDATE SET T.FirstName = S.FirstName, T.LastName = S.LastName;

DROP TABLE #Source;


Please visit the links
Link2
Link1
 
Share this answer
 
v2
Hi,

Try like this

SQL
INSERT INTO table1(Col1,Col2)
SELECT D.Col1, D.Col2
FROM (SELECT 'EDJ' Col1, 'LP' Col2
      UNION ALL SELECT 'AGE', 'LP'
	 UNION ALL SELECT 'DJR', 'VG') D 
WHERE NOT EXISTS (SELECT 1 FROM Table1 WHERE Col1=D.Col1 AND Col2=D.Col2 )



In Case of Direct Insert like "INSERT INTO Table_Name (Column_Name) VALUES()..." Go for INSERT with SELECT Statement.


Regards,
GVPrabu
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900