Stored procedure to insert image into SQL Server

r8xiu3jd  于 2023-06-21  发布在  SQL Server
关注(0)|答案(1)|浏览(136)

I want to store signatures in a SQL Server database table as VARBINARY(MAX). I use the following T-Sql to insert a signature:

INSERT INTO Signatures (UserID_FK, [Signature])
SELECT 2, BulkColumn
FROM OPENROWSET
(
    Bulk 'C:\Z_KB\SignatureTest.PNG', SINGLE_BLOB
) AS [Signature]

I want to turn this into a stored procedure, but it is not happy with the following:

CREATE PROCEDURE Insert_Signatures_SP
    (   
        @SignatureUri NVARCHAR(1000),
        @UserID INT
    )
AS
    INSERT INTO Signatures (UserID_FK, [Signature])
    SELECT @UserID, BulkColumn
    FROM OPENROWSET
    (
        Bulk @SignatureUri, SINGLE_BLOB
    ) AS [Signature]
GO

It is complaining that BulkColumn is invalid column name and it is looking for a string near Bulk.

I have changed it to the following, but now it says that @UserID must be declared:

CREATE PROCEDURE Insert_Signatures_SP
    (   
        @SignatureUri NVARCHAR(1000),
        @UserID INT
    )
AS
    DECLARE @sql VARCHAR(1000)

    SET @sql = 'INSERT INTO Signatures (UserID_FK, [Signature])
    SELECT @UserID , BulkColumn
    FROM OPENROWSET
    (
        Bulk '''+ @SignatureUri +''', SINGLE_BLOB
    ) AS [Signature]';

    EXEC(@sql)
GO

I have change it to the following, but it now says 'Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.':

CREATE PROCEDURE Insert_Signatures_SP
    (   
        @SignatureUri NVARCHAR(1000),
        @UserID INT
    )
AS
    DECLARE @err INT
    DECLARE @sql VARCHAR(1000)

    SET @sql = 'INSERT INTO Signatures (UserID_FK, [Signature])
    SELECT @UserID, BulkColumn
    FROM OPENROWSET
    (
        Bulk '''+ @SignatureUri +''', SINGLE_BLOB
    ) AS [Signature]';

    EXEC @err = sp_executesql @sql, N'@UserID INT', @UserID; 
    RETURN(@err);
GO

Trying to call it with:

EXEC Insert_Signatures_SP 'C:\Z_KB\SignTest.PNG', 3
ui7jx7zq

ui7jx7zq1#

@sql must be nvarchar(max) .

You should also correctly escape the URI using QUOTENAME

CREATE PROCEDURE Insert_Signatures_SP
(   
    @SignatureUri NVARCHAR(1000),
    @UserID INT
)
AS

SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = '
INSERT INTO Signatures (UserID_FK, [Signature])
SELECT @UserID, BulkColumn
FROM OPENROWSET
(
    BULK ' + QUOTENAME(@SignatureUri, '''') + ', SINGLE_BLOB
) AS [Signature];
';

EXEC sp_executesql @sql,
  N'@UserID INT',
  @UserID = @UserID; 

GO

相关问题