1

What is the simplest way to insert a Car for each user in Users and set the users CarID to the ID of the inserted Car?

[Users]

- ID
- Name
- CarID

[Cars]

- ID (Auto increment)
- Name

Sorry if this might be a duplicate question but I can't find any simple solutions. Everything I've found is using complicated cursors, pointers etc.

A simple and reusable syntax for this would save me hours while migrating data during system upgrades etc.

Jonas Stensved
  • 14,378
  • 5
  • 51
  • 80
  • The 'simplest' way would be to not use a system generated value to associate users with cars but instead use something that exists in the real world outside of the database, verifiable in reality, familiar to users, etc perhaps licence plate number or VIN. (Your cars have names?! perhaps use those :) – onedaywhen Feb 17 '12 at 11:37
  • You're right. But if it weren't I wouldn't ask :) – Jonas Stensved Feb 17 '12 at 12:30

3 Answers3

1

If you are on SQL Server 2008 or later you can use merge and output something like this.

Sample tables and data:

declare @Users table
(
  ID int identity primary key,
  Name varchar(10) not null,
  CarID int null
);

declare @Cars table
(
  ID int identity primary key,
  Name varchar(10) not null
);

insert into @Users(Name) values ('User1'),('User2'),('User3');

Add one care for each user and move the auto-generated CarID back to Users.

declare @ID table(CarID int, UserID int)

merge @Cars as C
using @Users as U
on 0 = 1
when not matched then
  insert (Name) values ('CarName')
output inserted.ID, U.ID into @ID;

update U
set CarID = I.CarID
from @Users as U
  inner join @ID as I
    on U.ID = I.UserID 

Try it out on SE Data.

More info on the merge/output trick can be found here.

Community
  • 1
  • 1
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
0

I'm assuming the code you're using lets you call stored procedures?

create procedure dbo.CarUserInsert_sp
(
@p_UserID int,
@p_UserName varchar(100),
@p_CarID int,
@p_CarName  varchar(100)
)
as

if not exists ( select 1 from Cars where ID = @p_CarID )
  insert Cars values ( @p_CarID, @p_CarName )

if exists (select 1 from Users where ID = @p_UserID )
  update Users set Name = @p_UserName, CarID = @p_CarID where ID = @p_UserID
else 
  insert Users values ( @p_UserID, @p_UserName,  @p_CarID )

go
Keith MacDonald
  • 218
  • 2
  • 7
0

try this:

insert into cars (name)
select distinct(name) from users

update user 
set carId = (select ID from cars where cars.name=user.Name)
Diego
  • 34,802
  • 21
  • 91
  • 134