3

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.

I want to use the data retrieved 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 do I use the SELECT result as the ProfileId Value.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The insert SQL should be:

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.

2 Comments

thanks for your replay, i am only select ProfileId from userId not both
When you include the parameter like this, it doesn't select from the user table, it substitutes the value directly in the SQL. So lets say @FriendProfileId is set to 23, the SELECT statement actually ends up being SELECT 23, ProfileID FROM user_profile...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.