Recently, I was assigned a very interesting project. I needed to insert all the document files and images in SQL table. In SQL, using BLOB data type, we can store various files in table. Now, we have a total of 250 files in one directory and I have accomplished this project without development team help.

To insert files in table, we can use “OpenRowset (Bulk, Single_Blob)”. You can find detailed syntax here. Now, as I have to insert 250 files in a single effort, I developed a dynamic script. All files are in one directory so it becomes very easy to do this using xp_dirtree.

Below is script

  1. /*Script to convert Files in varbinary and save in table
  2. Author: Nisarg Upadhyay
  3. Description: This script will perform bulk insert of BLOB files in SQL Table.
  4. */
  5. set nocount on
  6. create table FileList -- Table to store files
  7. (
  8. id int identity(1,1) primary key clustered,
  9. FileName varchar(max)
  10. )
  11. create Table #TempTable -- Table to store output of xp_dirtree
  12. (
  13. id int identity(1,1) primary key clustered,
  14. FileName varchar(max),
  15. FileDepth int,
  16. FileID int
  17. )
  18. CREATE TABLE dbo.TestBlob -- Table where BLOB will be stored
  19. (
  20. tbId int IDENTITY(1,1) NOT NULL,
  21. tbName varchar (50) NULL,
  22. tbDesc varchar (100) NULL,
  23. tbBin varbinary (max) NULL
  24. )
  25. insert into #TempTable EXEC master.sys.xp_dirtree 'E:\Scripts',0,1;
  26. insert into FileList (FileName) select 'E:\Scripts\' + Filename from #TempTable
  27. /*Bulk Insert Files in database*/
  28. declare @I int =0
  29. declare @FileName varchar(max)
  30. declare @Count int
  31. select * into #TempFileList from FileList
  32. set @Count=(select count(*) from #TempFileList)
  33. declare @SQLText nvarchar(max)
  34. While (@i<@Count)
  35. begin
  36. set @FileName=(select top 1 FileName from #TempFileList)
  37. set @SQLText='Insert TestBlob(tbName, tbDesc, tbBin) Select '''+@FileName+''',''Files'', BulkColumn from Openrowset( Bulk '''+@FileName+''', Single_Blob) as tb' --Here Instead of "Files" you can add
  38. exec @SQLText
  39. delete from #TempFileList where FileName=@FileName
  40. set @I=@I+1
  41. End
  42. drop table #TempFileList