Examples

Current Articles | Categories | Search

By David Dye @ Tuesday, July 15, 2008 5:18 PM :: 64 Views :: 0 Comments

 

The ability to insert a file into a VARBINARY(MAX) or VARCHAR(MAX) column using OPENROWSET is an awesome tool.  The obstacle comes when you wish to insert all or specific files from a foler into sql.  To do this you can use the System.IO namespace and utilizing directory and file objects you can iterate through all, or selected files in a path specified in the above clr stored procedure.  After deploying this proc I would recommend adding a default value to the extn input parameter of '*.*', which indicates all files.

Imports System

Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
 
 
Partial Public Class clr_sp_bulkload
    <Microsoft.SqlServer.Server.SqlProcedure()> _
    Public Shared Sub clr_sp_bulkload(ByVal clm As SqlString, ByVal tbl As SqlString, _
    ByVal dir As SqlString, ByVal extn As SqlString)
 
        'Declare variables and assign the values form the sql parameters
        'Trim the sql parameters to remove leading or trailing spaces that
        'might cause issues in code
 
        Dim sp As SqlPipe = SqlContext.Pipe()
        Dim cmd As New SqlCommand()
        Dim column As String = clm.ToString.Trim
        Dim table As String = tbl.ToString.Trim
        Dim dr As String = dir.ToString.Trim
        Dim flnm As String
        Dim ext As String = extn.ToString.Trim
 
        'Assure tha the directory exists
        If Directory.Exists(dr) Then
 
            'If the directory exists then loop through the files in the directory
            'path using the optional argument of the search criteria
            For Each flnm In Directory.GetFiles(dr, ext)
                Dim fi As New FileInfo(flnm)
 
                'Enter the try block to assure that there is not a lock on
                'the file that would cause an error
 
                Try
 
                    'The command is built using the input parameters
                    cmd.CommandText = " INSERT " & table & _
                    " SELECT * FROM OPENROWSET(BULK '" & _
                    fi.FullName.ToString & "',SINGLE_BLOB) AS x;"
 
                    'This will send the insert command to the Messages tab which will make it
                    'easier to troubleshoot as it executes the query
                    sp.Send(" INSERT " & table & _
                    " SELECT * FROM OPENROWSET(BULK '" & _
                    fi.FullName.ToString & "',SINGLE_BLOB) AS x;")
                    sp.ExecuteAndSend(cmd)
 
                Catch ex As Exception
                    sp.Send("File " & fi.FullName.ToString & " is not accessible")
 
                End Try
 
            Next
 
        Else
            sp.Send("The direcory does not exists or is inaccessible")
        End If
 
    End Sub

End Class

SQL CODE

 

 

Alter the proc to set a default value for the extn input parameter that will accept all files

ALTER
PROCEDURE [dbo].[clr_sp_bulkload]
     @clm [nvarchar](4000),
     @tbl [nvarchar](4000),
     @dir [nvarchar](4000),
     @extn [nvarchar](4000) = '*.*'
AS
EXTERNAL NAME [clr_sp_bulkload].[clr_sp_bulkload.clr_sp_bulkload].[clr_sp_bulkload]
GO

 

 Create a temp table to test the procedure

CREATE TABLE #temp(
col1 VARBINARY(MAX)

)

Excute the proc

 
EXEC dbo.clr_sp_bulkload 'col1', '#temp', 'C:\Documents and Settings\user\My Documents'
 
SELECT *
FROM [#temp]
 

 

Posted @ Tuesday, July 15, 2008 5:18 PM by David Dye
Previous Page | Next Page
Comments
Currently, there are no comments. Be the first to post one!
You must be logged in to post a comment. You can login here

Survey

Which of the following CLR objects are you currently using in SQL Server?




Submit Survey  View Results

Links

  Search

What's New

 Subscribe in a reader

Using CLR Impersonation to Access Resources Outside of SQL Server by Jonathan Kehayias

Traditionally if you had a need to access a file or other resource outside of SQL Server, the SQL Server service account was required to have appropriate file system access to the folder or path containing the file.  With CLR integration, this is no longer an absolute requirement.  Identity Impersonation will allow you to implicitly or explicitly change the execution context inside of a SQLCLR Function, Procedure, or Trigger. 

Using an Application Configuration (app.config/web.config) File in SQL Server CLR Integration by Jonathan Kehayias

A common part of programming in .NET is to use an configuration file to store configuration information in an easily modifiable location.  The app.config or web.config file is an invaluable inclusion in most .NET projects and developers may need to maintain this functionality as a part of logic sharing between objects in the database and the application as well.  This article will demonstrate how to configure your SQLCLR project to use Configuration Files in SQL.

Building a SAFE HttpUtility Class for SQL CLR by Jonathan Kehayias

This Article covers how to build a SQL Safe version of the System.Web.HttpUtility class methods HtmlEncode and HtmlDecode.  Source code is provided in the Examples area for these specific methods to be used in SQL CLR as User-Defined Functions with a SAFE Permission Set.

Recent Examples


Copyright 2007 by SQLCLR.net Terms Of Use Privacy Statement
Website graphics provided by Matt Green Designs
Page generated in 0.4218669 seconds.

All information and example code on this site is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from its use.

This site is in no way affiliated with Microsoft. Unless specifically stated otherwise, nothing should be construed to represent the official positions or opinions of Microsoft and/or its Employees.