Domanda

I have a code in my stored procedure:

create procedure [dbo].[add_codes](@codes code_type readonly, @id int)as
    insert into codes(code,value) 
           select code,'' value from @codes
           where code not in (select code from codes)

this should only insert the new values, ignoring duplicates but it does not and after some inserts when I check the count of code and distinct code they have different values. what is wrong with my code?

È stato utile?

Soluzione

NOT IN should work, but for something as simple as this, you could do something like:

INSERT INTO codes (code, value) 

SELECT DISTINCT
            code,
            '' AS value

FROM        @codes AS n

LEFT JOIN   codes AS c
    ON      n.code = c.code

WHERE       c.code IS NULL

Of course, it would be worthwhile to have a UNIQUE constraint set on the table as well.

Altri suggerimenti

NOT IN does work. If there is a single NULL value in codes, then NOT IN behaves a bit counter-intuitively. It works, but it works by always returning "false". That is because NULL is not a specific value, but an unknown value.

You should protect your code against this, if you use not in:

create procedure [dbo].[add_codes](@codes code_type readonly, @id int)
as begin
    insert into codes(code,value) 
           select code,'' value from @codes
           where code not in (select code from codes where code is false);
end;

I strongly agree with Rowland that the right way to approach this is with a unique constraint on the column that you want to be unique.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top