使用Select语句作为Insert语句值

时间:2020-12-24 07:43:53

Can you please help me with this statement, i am trying to retrieve data using SELECT statement and use the date in the INSERT statement.

你能帮我处理这个语句吗?我正在尝试使用SELECT语句检索数据并使用INSERT语句中的日期。

I want to use the data retrieved for ProfileId Value.

我想使用为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();
}

How do I use the SELECT result as the ProfileId Value.

如何使用SELECT结果作为ProfileId值。

2 个解决方案

#1


2  

The insert statement should be

插入语句应该是

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

or maybe SELECT TOP(1) ProfileId to make sure you will never get more than 1 value.

或者选择TOP(1) ProfileId,以确保不会得到超过1的值。

#2


1  

The insert SQL should be:

insert SQL应该是:

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

You just include the variables directly in the SELECT statement in the position corresponding to the column name.

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

#1


2  

The insert statement should be

插入语句应该是

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

or maybe SELECT TOP(1) ProfileId to make sure you will never get more than 1 value.

或者选择TOP(1) ProfileId,以确保不会得到超过1的值。

#2


1  

The insert SQL should be:

insert SQL应该是:

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

You just include the variables directly in the SELECT statement in the position corresponding to the column name.

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