T-SQL : How to run a subquery for each row in a insert statement ?

Hi !

I'm having trouble with a SQL query. I'm using MSSQL Server 2008

Here's the query :

INSERT INTO table
SELECT
NEWID() AS ID
,GETDATE() AS Modified
,'10436837-7AA9-4012-BE66-CA33D0FA084D' AS ModifiedByID
,'78C70790-BC9B-48DC-963B-164205D74655' AS AttributeID
,ID AS UserID
,(SELECT Top(1) value FROM UserAttributes WHERE AttributeID = '78C70790-BC9B-48DC-963B-164205D74655' AND Value > '5000' ORDER BY Value DESC) + 1 AS Value

FROM @emp1
GO

I would like that the sub-query in my insert statement be ran for each row inserted (this query go check that last assign employee number and add 1 for the next employee)

Is there a way to do this ?

Thanks

-Martin
Rubicon2009Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BrandonGalderisiCommented:
I see no logic that will prevent your subselect from returning the same record every time.  
LCSandman8301Commented:
since you are using sql server 2008. have you thought of using a ranking function to get your numbers
then all you need to do is get the starting place.
for example:
declare @startnum int
select @startnum = max(employeenumber)
from employeetable


SELECT 
NEWID() AS ID
,GETDATE() AS Modified
,'10436837-7AA9-4012-BE66-CA33D0FA084D' AS ModifiedByID
,'78C70790-BC9B-48DC-963B-164205D74655' AS AttributeID
,ID AS UserID
, @startnum + rownumber() over (order by id desc) as value
from [table]

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rubicon2009Author Commented:
@LCSandman8301

Thank You !
Rubicon2009Author Commented:
The solution was :

SELECT
      NEWID() AS ID
      ,GETDATE() AS Modified
      ,'10436837-7AA9-4012-BE66-CA33D0FA084D' AS ModifiedByID
      ,'78C70790-BC9B-48DC-963B-164205D74655' AS AttributeID
      ,ID AS UserID
      ,@VarLastEmpNumb + row_number() OVER(ORDER BY ID) AS Value
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.