How to read a file's contents into an SQL variable

Babu James picture Babu James · Jul 18, 2012 · Viewed 37.8k times · Source

Could someone tell me how to read a file's contents into an MS SQL variable using T-SQL?

Answer

Martin Smith picture Martin Smith · Jul 18, 2012
DECLARE @FileContents  VARCHAR(MAX)

SELECT @FileContents=BulkColumn
FROM   OPENROWSET(BULK'PathToYourFile.sql',SINGLE_BLOB) x; -- BINARY
--FROM OPENROWSET(BULK'PathToYourFile.sql',SINGLE_CLOB) x; -- CHAR

The SQL Server service account needs to have permissions to read the file obviously.