dnlnln / generate-sql-merge

Generate SQL MERGE statements with Table data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unable to generate merge script for tables with no primary key

abezulski opened this issue · comments

commented

I have dictionary tables that hold translated strings, ie. ComponentLoc with the following columns
ComponentId - foreign key to Components.Id
Name - holds translated name
Locale - foreign key to Locales.Id

When running SP
EXEC dbo.sp_generate_merge @schema = 'dbo', @table_name ='ComponentLoc'
I'm getting the following error:

Msg 50000, Level 16, State 1, Procedure sp_generate_merge, Line 452 [Batch Start Line 1]
Table has no primary keys. There should at least be one column in order to have a valid join.

The thing is that I can't add primary key to column Name; adding extra column just for the primary key doesn't make sense to me.

The tool currently needs the PK columns in order to uniquely match the rows of the static data (VALUES clause) to the destination table. For tables that don't have a PK, a parameter could potentially added to the tool so that it doesn't need to be physically added to the table itself.

However may I ask how your queries join onto or lookup data from ComponentLoc, for example, do they both use ComponentId and Locale to retrieve the Name?

commented

The temporary workaround here is to use composite key (WidgetId, Locale).
Here is the sample query:

SELECT c.Id, c.[Name], c.[Type], c.[SubType], cl.[Locale], cl.[Title], c.[DateCreated], c.[DateUpdated] FROM dbo.Components c INNER JOIN dbo.ComponentLoc cl ON cl.ComponentId = c.Id WHERE c.Id = @Id AND cl.Locale = @Locale

Thanks for providing those query details. Out of curiosity, is there any particular reason for not having the composite PK on the table permanently?

You can now generate a MERGE statement for a table that lacks a primary key using the newly-added @cols_to_join_on parameter (comma-separated, single-quote qualified string):

EXEC sp_generate_merge 'StateProvince', @schema = 'Person', @cols_to_join_on = "'StateProvinceCode'"