DonMax
DonMax

Reputation: 960

How to write this query in SQL server 2008

I have a requirement to insert more than one record into the table where the stored procedure will return the value for insertion. Please consider my logic.

Query Logic

foreach(var a in (select id from table1))
{
  insert into table2 values(a,DateTime.Now)
}

I need the same above logic needs to be done in SQL server. Any help to this solution will be appreciated.

Thanks,

Upvotes: 1

Views: 81

Answers (4)

DonMax
DonMax

Reputation: 960

I tried this and working well. Thanks to @Nikola Markovinović

insert into table2(idColumn, dateColumn) select id, getdate() from table1

Upvotes: 1

Nisha
Nisha

Reputation: 1439

declare @a int = 0, @n int, @i int = 1

select @n=COUNT(*) from table1 

while @i < @n
begin
insert into table2 values 
select x.a,Getdate() from 
(select ROW_NUMBER() over (order by [key]) as slno,* from table1 ) as x where  x.slno  = @i
set @i=@i+1;
end

Upvotes: 0

Amir Keshavarz
Amir Keshavarz

Reputation: 3118

declare @a int=0
while(@a<10)
begin
if(@a in (select id from table1))
begin
  insert into table2 values(a,DateTime.Now)
  set @a=@a+1
end
end

Upvotes: 1

Black.Jack
Black.Jack

Reputation: 1957

hope this helps..

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
IF @intFlag = 4
BREAK;
END
GO

Upvotes: 0

Related Questions