将值从一个表插入另一个表和其他附加值

时间:2015-04-04 13:13:44

标签: sql sql-server sql-insert

我有两个表 Users Friends 。我想为 ID 表中的不同用户复制两个 Users ,其中已经由C#代码提供了他们的名称,并将它们放入 Friends 表及其状态列将存储在 Friends 表的一行中。这是我的查询:

@id uniqueidentifier,
@username nvarchar(50),
@friendname nvarchar(50),
@friendstatus int
AS

INSERT INTO Friends (MYID,FriendId,ID,FriendStatus)
SELECT Users.ID,Users.ID,@id,@friendstatus
From Users cross join Friends as Friends_1
WHERE (Friends_1.MyID IN
          (SELECT ID
           FROM Users AS Users_1
           WHERE (UserName IN (@username)))) 
  AND (Friends_1.FriendId IN
          (SELECT ID
           FROM Users AS Users_1
           WHERE (UserName IN (@friendname))))

2 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西

INSERT INTO Friends (MYID,FriendId,ID,FriendStatus)

SELECT Users.ID, Users.ID, @id, @friendstatus
From Users 
inner join Friends as Friends_1 ON Users.ID = Friends_1.MyID 
                                OR Users.ID = Friends_1.FriendId 
WHERE UserName IN (@username, @friendname)

答案 1 :(得分:0)

我认为你可以通过这样的简单查询来实现:

insert into Friends (ID, MYID, FriendId, FriendStatus)
select 
    newid() ID,              -- you can generate a new ID in SQL Server
    -- @id ID                -- if you generate ID in your c# code: 
    u1.ID MYID, 
    u2.ID FriendId, 
    @friendstatus FriendStatus
from 
    users u1 
cross join 
    users u2
where 
    u1.UserName = @username
  and 
    u2.UserName = @friendname;