Click here to Skip to main content
Click here to Skip to main content

Read a file using transact-sql.

, 8 Jul 2010
Rate this:
Please Sign up or sign in to vote.
How easy to read a file without using of the seven extended stored procedures.

Introduction

To read the content of a file (for example read the text data from a *.txt, doc, rtf etc file) using transact-sql statement. We are familiar with the use of the seven extended stored procedures[^], especially when we want to read / write file and ole automation as well.
 
However; I would like to show you how easy to read a file without using of the seven extended stored procedures. We will use only the master.dbo.xp_cmdshell stored procedure for doing this.
 
For more information about master.dbo.xp_cmdshell stored procedure can be found at this link.[^]

A sample sql script is given below:

Script
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--      Author:	Md. Marufuzzaman.
-- Create date: 
-- Description:	Get the content from files. 
-- =============================================
-- EXEC [dbo].[spGetText] @Path = 'C:\MyTextFile.txt'

ALTER PROCEDURE [dbo].[spGetText] 
(
	@Path	VARCHAR(500)
)
AS
BEGIN
 
DECLARE @Command VARCHAR(255)
SELECT @Path = ISNULL(@Path,'C:\Windows\System32\license.rtf') 
PRINT 'Path: ' + @Path
 
CREATE TABLE #Xml(dataRow VARCHAR(MAX))
	IF @Path IS NOT NULL AND LEN(@Path) > 10
		BEGIN
			SELECT @Command = 'type ' + @Path
			INSERT INTO [dbo].[#Xml] 
					EXEC master.dbo.xp_cmdshell @Command
		END
	IF @@ROWCOUNT <> 0
		BEGIN
			SELECT * FROM [dbo].[#Xml]
		END
			
DROP TABLE #Xml
 
END
GO
 

License

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

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
n/a
Follow on   Twitter

Comments and Discussions

 
GeneralYou realize your @Command variable is too small for your 500... PinmemberAndrew Rissing8-Jul-10 4:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 8 Jul 2010
Article Copyright 2010 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid