I’m wanting to throw an error when reference keys are missing, however instead of failing through a integrity check, I want to list out the missing keys. I’ve created the below which works. However I’m hoping there is a way to optimise it and reduce the number of lines of code.
DECLARE @NonRefKeys INT
SELECT @NonRefKeys = SUM(1)
FROM staging.Sale sa
WHERE NOT EXISTS (
SELECT cu.Customer_Shipping_ID
FROM staging.Customer cu
WHERE LTRIM(RTRIM(sa.Customer_Shipping_ID)) = LTRIM(RTRIM(cu.Customer_Shipping_ID)))
IF @NonRefKeys IS NOT NULL
BEGIN
IF OBJECT_ID('tempdb..#Missing_Ref') IS NOT NULL
DROP TABLE #Missing_Ref;
SELECT sa.Customer_Shipping_ID AS ID
INTO #Missing_Ref
FROM staging.Sale sa
WHERE NOT EXISTS (
SELECT cu.Customer_Shipping_ID
FROM staging.Customer cu
WHERE LTRIM(RTRIM(sa.Customer_Shipping_ID)) = LTRIM(RTRIM(cu.Customer_Shipping_ID)))
DECLARE @Current_ID VARCHAR(50);
DECLARE @Missing_ID VARCHAR(MAX) = '';
DECLARE @Output_Error VARCHAR(MAX);
DECLARE id_cursor CURSOR FOR
SELECT ID
FROM #Missing_Ref;
OPEN id_cursor
FETCH NEXT FROM id_cursor INTO @Current_ID
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@Missing_ID != '')
SET @Missing_ID = @Missing_ID + ', ';
SET @Missing_ID = @Missing_ID + @Current_ID;
FETCH NEXT FROM id_cursor INTO @Current_ID
END
CLOSE id_cursor
DEALLOCATE id_cursor
SET @Output_Error = 'ERROR: Key/s ' + @Missing_ID + ' for Customer Shipping ID missing from Customer table';
RAISERROR (@Output_Error,16,1)
END
Check this out… you can update a variable without having to create a temp table
There is a trailing “,” that you have to remove.
The
Updatestatement in my example can be replaced with one of your tables like this (OTTOMH, so syntax may need to be verified)Now, if you’re good with using XML, here is another cool method: