I want to create dymamic SQL code to automatically create a table-replication.
I’m stuck on how to make the following code dynamic, so that it’s possible to pass in SQL variables and use them in the code. I help myself at the moment with search and replacing the 'TODO:' parts, which is not very nice… Here is the code:
DECLARE @sql VARCHAR(MAX) SET @sql = '' SELECT @sql = @sql + 'exec sp_addarticle @publication = ''TODO:TREP_PUBLICATION_NAME'',@article = N''' + name + ''', @source_owner = N''dbo'', @source_object = N''' + name + ''', @type = N''logbased'', @description = N'''', @creation_script = N'''', @pre_creation_cmd = N''delete'', @schema_option = 0x0000000000000000, @identityrangemanagementoption = N''none'', @destination_table = N''' + name + ''', @destination_owner = N''dbo'', @status = 8, @vertical_partition = N''false'', @ins_cmd = N''SQL'', @del_cmd = N''SQL'', @upd_cmd = N''SQL''' FROM TODO:PUBLICATION_DB.sys.tables WHERE type = 'U' AND name IN ( SELECT name FROM OPENROWSET('SQLOLEDB', 'TODO:SUBSCRIBER_SERVER'; 'TODO:SUBSCRIBER_LOGIN'; 'TODO:SUBSCRIBER_PASSWORD', 'select * from TODO:SUBSCRIBER_DB.sys.tables where type=''U''') ) AND name IN ( SELECT TABLE_NAME FROM TODO:PUBLICATION_DB.INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TODO:TABLE_NAME_FILTER ) EXEC(@Sql)
One problem is that I need dynamic SQL inside a dynamic SQL block. If somebody could help me to convert this code using variables I would really appreciate that!
Thanks Daniel
Dynamic SQL might not be the answer – but that doesn’t mean you can’t make it easier to automate and ‘parameter-ize’.
In other words, I once managed a huge replication topology where I frequently had to tear down subscribers, and even (occasionally) recreate publications, and so on. Rather than mucking with trying to generate T-SQL that dynamically queried things and did EVERYTHING in one fell-swoop, I create a number of T-SQL Templates (.tql files) that I could then use to populate with a few parameters, and then turn loose.
And if you’re unfamiliar with templates, just check out this video – which will quickly get you up to speed:
http://www.sqlservervideos.com/video/using-sql-server-templates
And here’s an example of the kind of template I was using to add articles – as you’re shooting for:
And in some cases… I also used these templates which in turn had some nested/dynamic SQL. But by using both, I found that I was able to very easily tame some of the more redundant tasks necessary without over-complicating things.