I'm using stored procedures in my excel vba code to pass data to the sql server and send a return message back to the vba code. Well, I read a lot in other question topics on this and other sites, but I couldn't find the best solution for this approach. To give you a better imagination, I display an example:
VBA Code:
// defined vba function to return message from database to gui
Public Function fGetMessage() As String
' Declare variable and store the data id in the .Tag of userform
Dim lngVarId As Long
lngVarId = UserForm1.tbVar.Tag
' Instance of ADODB.Connection
Dim oDatabase As clsDatabase
Set oDatabase = New clsDatabase
' send sql statement with sproc to sql server and get a return message from database
Dim oCmd As ADODB.Command
Set oCmd = New ADODB.Command
With oCmd
.ActiveConnection = oDatabase.fGetDbConnection()
.CommandType = adCmdStoredProc
.CommandText = "dbo.spDeleteProtocolData"
.Parameters(1) = lngVarId
Dim oRs As ADODB.Recordset
Set oRs = New ADODB.Recordset
Set oRs = oCmd.Execute
End With
fGetDeleteMessage = oCmd.Fields("ReturnMessage") // here I want the string return message
End Function
SQL-Server:
// defined stored procedure in sql server
CREATE PROCEDURE dbo.spDeleteProtocolData
@VarId AS INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
UPDATE dbo.vProtocolData
SET StatusId = 0
WHERE VarId = @VarId
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- store error message in log table
INSERT INTO dbo.Logs (ErrNumber, ErrLine, ErrState, ErrSeverity, ErrSProc, ErrMessage, CreatedBy, CreatedAt)
SELECT ERROR_NUMBER(), ERROR_LINE(), ERROR_STATE(), ERROR_SEVERITY(), ERROR_PROCEDURE(), ERROR_MESSAGE(), CURRENT_USER, GETDATE()
ROLLBACK TRANSACTION
END CATCH
END
GO
Does anyone have an idea or a better solution to handle return messages between vba excel and sql server database?