I'm constructing a stored procedure for Insert only. What rows I want to insert to my target table depend on a composite key of fields. I'm trying to construct it before and then use it in the WHERE-clause, but I get this error:
An expression of non-boolean type specified in a context where a condition is expected, near ')'*
My @WhereClause is holding this value from the string split:
[Column1] = S.[Column1] AND [Column2] = S.[Column2] AND [Column3] = S.[Column3]
This is my code
AS
BEGIN
SET XACT_ABORT ON
DECLARE @compositeKey NVARCHAR(MAX) = 'Column1,Column2,Column3';
DECLARE @WhereClause NVARCHAR(MAX) = '';
BEGIN TRY
BEGIN TRANSACTION
SELECT @WhereClause = STRING_AGG(QUOTENAME(Value) + ' = S.' + QUOTENAME(Value), ' AND ')
FROM STRING_SPLIT(@compositeKey, ',');
PRINT @WhereClause;
INSERT INTO [target].[targetTable]
(
Bunch of columns...
)
SELECT
Bunch of columns...
FROM [source].[sourceTable] AS S
WHERE NOT EXISTS (
SELECT 1 FROM [target].[targetTable]
WHERE + @WhereClause
);
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@trancount > 0 ROLLBACK TRANSACTION
DECLARE @msg nvarchar(2048) = error_message()
RAISERROR (@msg, 16, 1)
RETURN 55555
END CATCH
END
It works if I put the result from my stringsplit directly behind the Where, that's why I thought I would work with the variable.