Translate to your Language

Friday, July 26, 2013

Sql Server Sp to Read row by row from a table and create a file for each row- Without Cursor

by Unknown  |  in Other at  6:11 AM

Here is the Sp,

1) Creates a temp table called t1
2) Store all data from table to temp table t1
3) Count the number of rows from the table and store in a variable
4) select top 1 row from the temp table
5) Create the file name by combaning values from the table
6) out put the value to the file
7) Delete the processed row from the table
8) move to the next line

declare @SQL varchar(8000)
declare @counter intdeclare
@maxrows intdeclare
@filename varchar(30)declare @count intdeclare
@id varchar(50)declare @id1 varchar(30)declare @id3 varchar(50)DECLARE @Statement VARCHAR(8000)select @counter=1, @maxrows = 0
create table t1(cola varchar(50), colb varchar(30), colc varchar(50),cold varchar(max))
insert into t1 SELECT c1,c2,c3,c4 FROM Tableselect @count=(select COUNT(1) from t1)while (@count <>0)beginselect @id = (select top 1 cola from t1)select @id1 = (select top 1 colb from t1)select @id3 = (select top 1 colc from t1)select @filename =(select top 1 cola + '_'+colb +'_'+colc from t1)SET @SQL ='SET NOCOUNT ON select cast(cold as varchar(max)) from t1 where cola=' + @id + ' and colb=' + @id1 + ' and colc=' + @id3 + ' 'print @SQLSET @Statement = 'sqlcmd -E -S <servername> -d <dbname> -h -1 -y 0 -q "' + @SQL + '" > "C:\' + @filename + '.txt"' EXEC xp_cmdshell @Statement delete from t1 where cola=@id and colb=@id1 and colc=@id3set @count=@count-1end
drop
table t1

0 comments:

© Copyright © 2015Big Data - DW & BI. by