Translate of the Code statement

Kenny Gua 431 Reputation points
2021-05-30T04:12:01.693+00:00

Hi, what is the exact logic of the following SP code. I want to translate this logic in Select statement to know the following logic and know the reason of the error which is
'Code field is not unique'. Thanks

/* cannot insert code in "CodeSection" if "code" is not unique */

DECLARE @Codenum VARCHAR(256)
declare @acount int

SELECT @Codenum=',111222222,111222233,'

select @acount=count(*) from CodeSection t2
where [Codenum] is not NULL
AND ISNULL(@Codenum, '') NOT LIKE '%,' + ISNULL([code], '') + ',%'
if @acount > 1
raiserror('Code field is not unique', 16, 10)
return

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,682 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 119.2K Reputation points
    2021-05-30T08:30:21.057+00:00

    I think that the approximate translation is: “if the CodeSection table contains two or more rows where Codenum column is not null and code column is not 111222222 and not 111222233, then ‘Code field is not unique’”.

    If you need a different functionality, then the query can be adjusted.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 115.9K Reputation points MVP
    2021-05-30T08:40:39.947+00:00

    The code does not really make sense to me. First, if this is from a stored procedure, why is @Codenum set to a constant value before checking?

    Even if we overlook that: The operator is NOT LIKE, so this means that as we find two rows which do not match @Codenum, we start yelling about the code not being unique.

    LIKE would make a little more sense. Then you have a comma-separated string, which also has commas in the start and the end, and this compared to a pattern with a leading and closing wildcard and with commas on both sides. So if a row has code 123, you would be comparing @Codenum to %,123,%, and if @Codenum goes ,123,456,789,, there is a match.

    But even then it's kind of funny. Since the condition is @account > 1, this means that one duplicate is permitted - but not two.

    Also, the code does not consider that there may be duplicates in @Codenum itself.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.