SQLUSA

Microsoft SQL Server 2005 Best Practices

How to export data directly into a flat file?

 

Execute the following script in Query Editor to create a sproc which exports directly to a flat file using nested cursors:

USE AdventureWorks;
GO


CREATE PROC SupplierProductSummary @FilePath varchar(100)
AS
BEGIN
DECLARE @Line nvarchar(1000)
DECLARE @Command nvarchar(2000)
DECLARE @Return int

DECLARE @VendorID int, @VendorName nvarchar(50)
DECLARE @ProductName nvarchar(50)

SET @Line='******** SUPPLIERS PRODUCTS REPORT ********'
SET @Command= 'echo ' + @Line + ' >>'+ @FilePath
EXEC @Return = master..xp_cmdshell @Command , no_output

DECLARE curVendor CURSOR FOR
SELECT VendorID, Name
FROM Purchasing.Vendor
WHERE CreditRating = 1
ORDER BY VendorID

OPEN curVendor

FETCH NEXT FROM curVendor
INTO @VendorID, @VendorName

WHILE @@FETCH_STATUS = 0
BEGIN

SET @Line='. '
SET @Command= 'echo ' + @Line + ' >>'+ @FilePath
EXEC @Return = master..xp_cmdshell @Command , no_output
SET @Line='***** Products From Supplier: ' + @VendorName
SET @Command= 'echo ' + @Line + ' >>'+ @FilePath
EXEC @Return = master..xp_cmdshell @Command , no_output

DECLARE curProduct CURSOR FOR
SELECT v.Name
FROM Purchasing.ProductVendor pv, Production.Product v
WHERE pv.ProductID = v.ProductID AND
pv.VendorID = @VendorID

OPEN curProduct
FETCH NEXT FROM curProduct INTO @ProductName

IF @@FETCH_STATUS <> 0
BEGIN
SET @Line='*** NO PRODUCTS AVAILABLE AT THIS TIME *** '
SET @Command= 'echo ' + @Line + ' >>'+ @FilePath
EXEC @Return = master..xp_cmdshell @Command , no_output
END

WHILE @@FETCH_STATUS = 0
BEGIN

SET @Line=' ' + @ProductName
SET @Command= 'echo ' + @Line + ' >>'+ @FilePath
EXEC @Return = master..xp_cmdshell @Command , no_output
FETCH NEXT FROM curProduct INTO @ProductName

END

CLOSE curProduct
DEALLOCATE curProduct

FETCH NEXT FROM curVendor
INTO @VendorID, @VendorName
END
CLOSE curVendor
DEALLOCATE curVendor
END

GO

exec SupplierProductSummary 'F:\data\SUPPreport4.txt'


 

SQLUSA - The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page