使用Select语句插入语句值

时间:2014-12-24 22:02:10

标签: c# asp.net visual-studio-2010

请您帮我解释一下这句话,我试图使用SELECT语句检索数据并使用INSERT语句中的日期。

我想使用为ProfileId值检索的数据。

 // Get the UserId of the just-added user
    MembershipUser currentUser = Membership.GetUser();
    Guid currentUserId = (Guid)currentUser.ProviderUserKey;

// Insert a new record into UserPro
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

string insertSql = "INSERT INTO User_Friend(ProfileId1, ProfileId) VALUES(@FriendProfileId) SELECT ProfileId FROM User_Profile WHERE UserId = (@UserId)";


using (SqlConnection myConnection = new SqlConnection(connectionString))
{
    myConnection.Open();
    SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
    myCommand.Parameters.AddWithValue("@FriendProfileId", Request.QueryString["ProfileId"].ToString());

    myCommand.Parameters.AddWithValue("@UserId", currentUserId);
    myCommand.ExecuteNonQuery();
    myConnection.Close();
}

如何将SELECT结果用作ProfileId值。

2 个答案:

答案 0 :(得分:2)

insert语句应为

INSERT INTO User_Friend(ProfileId1, ProfileId)
VALUES ( @FriendProfileId, 
         (SELECT ProfileId FROM User_Profile WHERE UserId = @UserId))

或者SELECT TOP(1) ProfileId以确保您永远不会获得超过1个值。

答案 1 :(得分:1)

插入SQL应为:

string insertSql = "INSERT INTO User_Friend(ProfileId1, ProfileId) SELECT @FriendProfileId, ProfileId FROM User_Profile WHERE UserId = (@UserId)";

您只需将变量直接包含在SELECT语句中与列名对应的位置。