Sample code for 30+ languages & platforms
SQL Server

Import a Certificate (.cer file) into a Windows Certificate Store

See more Certificates Examples

Demonstrates how to import a certificate (without private key) into a Windows certificate store.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    DECLARE @cert int
    EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @cert, 'LoadFromFile', @success OUT, 'qa_data/certs/example.cer'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @cert, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @cert
        RETURN
      END

    DECLARE @certStoreCU int
    EXEC @hr = sp_OACreate 'Chilkat.CertStore', @certStoreCU OUT

    DECLARE @readOnlyFlag int
    SELECT @readOnlyFlag = 0

    -- "CurrentUser" and "My" are the exact keywords to select your user account's certificate store.
    EXEC sp_OAMethod @certStoreCU, 'OpenWindowsStore', @success OUT, 'CurrentUser', 'My', @readOnlyFlag
    IF @success = 0
      BEGIN

        PRINT 'Failed to open the CurrentUser/My certificate store for read/write.'
        EXEC @hr = sp_OADestroy @cert
        EXEC @hr = sp_OADestroy @certStoreCU
        RETURN
      END

    -- Import the certificate into the CurrentUser/My certificate store.
    EXEC sp_OAMethod @certStoreCU, 'AddCertificate', @success OUT, @cert
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @certStoreCU, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @cert
        EXEC @hr = sp_OADestroy @certStoreCU
        RETURN
      END


    EXEC sp_OAGetProperty @cert, 'SubjectCN', @sTmp0 OUT
    PRINT 'Imported ' + @sTmp0

    PRINT 'Success.'

    EXEC @hr = sp_OADestroy @cert
    EXEC @hr = sp_OADestroy @certStoreCU


END
GO