views:

310

answers:

3

I am using OleDB for executing my queries in C#,

Is there any way I can execute multiple queries in one command statement?

I tried to separate them with semi-colon (;) but it gives error "Characters found at the end"

I have to execute a few hundreds of queries at once.

Edit: I am executing Insert Statements.

A: 

Simply Batch them up using GO (groups a batch) and colons to separate queries inside a batch. Make sure to surround your colon with spaces. You need to submit this SQL to sp_executesql.

BEGIN TRANSACTION
GO
USE AdventureWorks;
GO
CREATE TABLE dbo.mycompanies
(
 id_num int IDENTITY(100, 5),
 company_name nvarchar(100)
)
GO
INSERT mycompanies (company_name)
   VALUES (N'A Bike Store');
INSERT mycompanies (company_name)
   VALUES (N'Progressive Sports');
INSERT mycompanies (company_name)
   VALUES (N'Modular Cycle Systems');
INSERT mycompanies (company_name)
   VALUES (N'Advanced Bike Components');
INSERT mycompanies (company_name)
   VALUES (N'Metropolitan Sports Supply');
INSERT mycompanies (company_name)
   VALUES (N'Aerobic Exercise Company');
INSERT mycompanies (company_name)
   VALUES (N'Associated Bikes');
INSERT mycompanies (company_name)
   VALUES (N'Exemplary Cycles');
GO

SELECT id_num, company_name
FROM dbo.mycompanies
ORDER BY company_name ASC;
GO
COMMIT;
GO

Example taken from MSDN.

Johannes Rudolph
`GO` only applies to Microsoft SQL Server Management Studio. It is used to break statements up, and hence will not work when using `OleDbCommand`
Codesleuth
GO can be used when executing your statement via sp_executesql.
Johannes Rudolph
+1  A: 
Codesleuth
A: 

Use sp_executesql.

Do see my answer in another question where I include a sample usage of sp_executesql to send SQL queries in a batch.

Amry