views:

40

answers:

2

How can I write this code in T-SQL?

var categories = new []{ "cat1", "another category", "one more" };
for (var i = 0; i<categories.count; i++)
{
    insert into Categories (id, name)
    values (i, categories[i])
}

Is it possible?

+4  A: 

Sql Server 2008 allows inserting multiple record in a single INSERT statement:

INSERT INTO Categories (id, name)
VALUES (0, 'cat1'),
    (1, 'another category'),
    (2, 'one more')
devio
This exactly what I'm looking for.
stacker
A: 

You have two options:

1) Just use a memory table (and no loop), which will achieve the same result:

declare @values table (idx int identity(0, 1), value varchar(50))

insert into @values (value) values('cat1')
insert into @values (value) values('cat2')
insert into @values (value) values('cat3')

insert into Categories (id, name) select idx, value from @values

2) Use a memory table and construct an equivalent loop

declare @values table (idx int identity(0, 1), value varchar(50))

insert into @values (value) values('cat1')
insert into @values (value) values('cat2')
insert into @values (value) values('cat3')

declare @i int
declare @cnt int

select @i = min(idx), @cnt = max(idx) + 1 from @values

while(@i < @cnt)
begin
    insert into Categories (id, name) 
        select @i, value from @values where idx = @i

    select @i = @i + 1
end

The first option will achieve the same results, but it is not a loop (which is what you asked for).

Adam Robinson