Excel VBA: Insert record into MS SQL database

VAer-4038 771 Reputation points
2021-10-26T22:48:37.123+00:00

The code worked fine with Sybase, now database has been moved to MS SQL, and it runs into error. It seems that it has issue to run INSERT INTO or UPDATE code.

What does error mean? object in the screenshot is table_name.

Thanks.

143916-ms-sql.jpg

Set CnDev = CreateObject("ADODB.Connection")  
CnDev.Open ConnectionString  
  
TestQuery = "INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...)”  
  
  
Set TestRs = CreateObject("ADODB.Recordset")  
          
TestRs.Open TestQuery, CnDev  
          
Set TestRs = Nothing  
  
Developer technologies Visual Basic for Applications
SQL Server Other
{count} vote

Accepted answer
  1. Shalvin 161 Reputation points
    2021-10-27T00:29:52.213+00:00

    Hi @VAer-4038 ,

    There could be multiple reasons for this failure. The most common reason would be that the user you are using in connection string might not have INSERT permission. Please use the steps in grant-transact-sql to GRANT INSERT permission to the user. Even if user has permission, would suggest removing and them and granting again.

    Use the following query to grant permission to a specific table.

    GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.table_name TO user_name;  
    

    Use the following query to grant write permission to all tables.

    EXEC sp_addrolemember N'db_datawriter', N'user_name';  
    

    Another reason for the error is that there could be a trigger on the table preventing insert. In that case, you may need to check with DBAs and act accordingly.

    Please let us know if the issue is fixed after above steps.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.