Showing posts sorted by date for query bulk insert. Sort by relevance Show all posts
Showing posts sorted by date for query bulk insert. Sort by relevance Show all posts
Thursday, April 26, 2007

Bulk insert with dynamic primary key -SQL Server 2000/2005

You often need a bulk insert with dynamic primary key where you can define your keys without getting it from the .txt files or .csv files.

here are the stored procedure to bulk insert country with dynamic primary key.

first create temp.txt file in c drive with following data.

Australia
Canada
America
India

then create table with following fields

countryid int 4
countryname varchar(100)

and assign name as tblCountryMaster

now use following stored procedure


SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE sp_BulkInsertCountry
(
@FilePath varchar(1000)
)
AS
BEGIN--PROCEDURE
--variable declaration
declare @SQL varchar(500)
declare @id int
declare @CountryName varchar(30)


--Create temporary table for Country
CREATE TABLE #tmpCountry
(
CountryName varchar(30),
)

---executing bulk insert on temporary table
SET @SQL='BULK INSERT #tmpCountry from ''' + @FilePath + ''' WITH (FIELDTERMINATOR ='','',ROWTERMINATOR=''\n'')'
EXEC(@sql)

DECLARE cursor_Country CURSOR READ_ONLY FOR
select [CountryName] from #tmpCountry

OPEN cursor_Country
FETCH NEXT FROM cursor_Country INTO @CountryName
WHILE @@FETCH_STATUS=0
BEGIN
SELECT @id=isnull(max(Countryid),0) from tblCountryMaster
SET @id=@id+1
INSERT INTO tblCountryMaster values(@Id,@CountryName)
FETCH NEXT FROM cursor_Country INTO @CountryName
END
CLOSE cursor_Country
DEALLOCATE cursor_Country
END--PROCEDURE


GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

happy programming
Share:
Thursday, March 1, 2007

Stored Procedure-Importing CSV Files into Table -SQL Server

Here is the Stored Procedure code for importing comma seperated CSV files to table.


CREATE PROCEDURE [dbo].[sp_ImportScript]
@filepath varchar(2000)
AS
BEGIN TRY
declare @tmpsql varchar(3000)
set @tmpsql='BULK INSERT table'
set @tmpsql=@tmpsql + ' FROM ''' + @filepath + ''''
set @tmpsql=@tmpsql + ' WITH (FIRSTROW=2,FIELDTERMINATOR ='
set @tmpsql=@tmpsql + ''','''
set @tmpsql=@tmpsql + ',ROWTERMINATOR ='
set @tmpsql=@tmpsql + ''','''
set @tmpsql=@tmpsql + ')'
EXEC(@tmpsql)
select @@rowcount
END TRY
BEGIN CATCH
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews