I have an insert trigger that contains dynamic sql stored as a resource for my XE2 project. It also contains placeholders for the database name and table name that are substituted when the Delph code runs to execute the SQL.
Originally I was using the DevArt SQL Server driver against a SqlExpress database, but am now wanting to use ODBC and the SQL Native Client driver against a LocalDB database.
What I have found is that my original create trigger scripts no longer work.
I am using TSQLQuery.ExecSQL to execute my SQL commands.
CREATE TRIGGER [dbo].[#TableName#_INSERT_TRIGGER] ON [#DatabaseName#].[dbo].[#TableName#] FOR INSERT
causes a
'[Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot create trigger on 'EvaluationCompany_COPYDB.dbo.COPY_PRODUCTS' as the target is not in the current database.'
The parser class I use does split SQL scripts at the GO keyword into separate statements, so I amended my create trigger script to say
USE [#DatabaseName#]
GO
CREATE TRIGGER [dbo].[#TableName#_INSERT_TRIGGER] ON [dbo].[#TableName#] FOR INSERT
which is what you would do in SSMS but that says
'[Microsoft][SQL Server Native Client 11.0][SQL Server]The object 'dbo.COPY_PRODUCTS' does not exist or is invalid for this operation.'
Probably because the "current database" for the CREATE is not the one set by USE, as it seems to be forgotten.
I tried my usual way of stringing sql statements into a single execute by doing
USE [#DatabaseName#];
CREATE TRIGGER [dbo].[#TableName#_INSERT_TRIGGER] ON [dbo].[#TableName#] FOR INSERT
but that throws the expected
'[Microsoft][SQL Server Native Client 11.0][SQL Server]'CREATE TRIGGER' must be the first statement in a query batch.'
So I wrapped the whole CREATE...END in a EXEC [#DatabaseName#].[sys].[sp_ExecuteSQL] N' ' and tried to execute that. If I paste the contents of the string variable into SSMS it executes fine, but when passed to the ExecSQL, it says
'[Microsoft][SQL Server Native Client 11.0][SQL Server]The request for procedure 'sp_executesql' failed because 'sp_executesql' is a procedure object.'
which is kind of nonsensical. So now I am at a loss as to how to create a trigger on a table using dbExpress and the SQL Server native client.