I just want to make sure I am doing this right.
I have two tables:
Customer:
ID: GUID
name: varchar
... etc
and Reference
ID: GUID
customerid: GUID ----> FK
Myreference: varchar (max)
timestamp: datetime
I have the following stored procedure which check the reference table if the reference is already being used by another customers.
@CustomerId [uniqueidentifier],
@Myreference [nvarchar]
AS
BEGIN
SELECT
CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT) AS IsInUse
FROM Reference
WHERE CustomerId <> @CustomerId AND Myreference= @Myreference
END
GO
Now, I need to change the stored procedure to check if the reference is used by another customer to check if that other customer has another reference record then return 0 otherwise return 1.
Here is my change, but I am pretty sure it can be better.
IF (SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT) AS IsInUse
FROM Reference
WHERE CustomerId <> @CustomerId AND
Myreference = @Myreference ) = 1
BEGIN
SELECT CAST(CASE WHEN COUNT(*) > 1 THEN 0 ELSE 1 END AS BIT) AS IsFine
FROM Reference
WHERE CustomerId = (SELECT CustomerId
FROM Purchase.BureauCreditEnquiry
WHERE CustomerId <> @CustomerId AND
Myreference = @Myreference );
END;
ELSE
BEGIN
SELECT 0;
END;
since this is stored procedure
, use sql
variables.
DECLARE @IsInUse INT
DECLARE @isFine INT
SET @IsInUse = SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT) AS IsInUse
FROM Reference
WHERE CustomerId <> @CustomerId AND
Myreference = @Myreference
SET @isFine = SELECT CAST(CASE WHEN COUNT(*) > 1 THEN 0 ELSE 1 END AS BIT) AS IsFine
FROM Reference
WHERE CustomerId = (SELECT CustomerId
FROM Purchase.BureauCreditEnquiry
WHERE CustomerId <> @CustomerId AND
Myreference = @Myreference )
SELECT IIF(@IsInUse >= 1, @isFine, 0)