简体   繁体   中英

SQL Server 2005 Bulk insert on split string where not exists

I have a problem with an insert statement where I cannot get the "where not exists" clause to work. I would prefer a solution where I do not have to dump my list into a declared a table. Here are two of the solutions I have tried, could someone please tell where my syntax is wrong? My split string list has three values, the first two values would be new, but the third value already exists in the database and so should not be inserted.

With this sample I get no data returned at all:

 insert into dbo.Cook(Id, CookId, DateEntered, Active) 
    select 
        @Id, value as CookId, getDate(), 1 
    from 
        dbo.Split('123456,234567,345678', ',')
    left join 
       dbo.Cook ck on ck.Id = @Id
    where 
       not exists (select CookId from dbo.Cook where Id = @Id)

Then I tried a version with a table which winds up returning all the values in my @ids table including the cook number that would be a duplicate:

 declare @ids table (id int)

 insert into @ids 
     select value as id 
     from dbo.Split('123456,234567,345678', ',')

 insert into dbo.Cook(Id, CookId, DateEntered, Active) 
    select 
       @Id, id as CookId, getDate(), 1 
    from 
       @ids
    left outer join 
       dbo.Cook ck on ck.CookId = id
    where 
       not exists (select CookId from dbo.Cook where ck.CookId != id)

Aside from your neglecting to put your from clause on a new line cringe , I believe it is your syntax.

I don't understand what you are trying to do here. dbo.Split is not a built in function in SQL Server as far as I know.

I have the solution to my problem, thanks goes out to a fellow programmer. My problem was I should have being doing the join on the select statement and adding a comparison column to get the information I was looking for. The solution was this:

insert into dbo.Cook(Id, CookId, DateEntered, Active) 
select 
    @Id, value as CookId, getDate(), 1
from 
    dbo.Split('123456,234567,345678', ',') c
left join 
   (select cook from dbo.Cook where Id = @Id) cook on cook.Id = c.value
where 
   cook.Id is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM