Thursday, October 13, 2005

Read from a text file into SQL table without BCP

One of my co-workers asked how to read a text file into a table.

Without using BCP, here is one way of doing it... (must have xp_cmdshell enabled.)

-- This procedure reads the ALL text file which contains the currently
-- running date and displays the results

DECLARE @FileCommand as varchar(255)
SET @FileCommand = 'type c:\all.txt'
-- =============================================
-- Create table basic template
-- =============================================
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = 'TempDateCheck'
AND type = 'U')
DROP TABLE TempDateCheck

CREATE TABLE TempDateCheck (
Contents varchar(100) NULL)

INSERT INTO TempDateCheck
EXEC xp_cmdshell @FileCommand

SELECT Contents
FROM TempDateCheck

No comments: