Using a Select Statement on a Statement Statement

Could you please help me with this statement, I am trying to get data using SELECT statement and use date in statement INSERT

.

I want to use the data I got for ProfileId

Value.

 // 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 to use the result SELECT

as meaning ProfileId

.

+3


source to share


2 answers


The insert statement should be

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

      



or perhaps SELECT TOP(1) ProfileId

to make sure you never get more than 1 value.

+2


source


The SQL insert should be:

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

      



You simply include the variables directly in the statement SELECT

at the position corresponding to the column name.

+1


source







All Articles