Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Select statement for Insert Statement Value

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.

like image 250
Carter Willams Avatar asked Nov 20 '25 03:11

Carter Willams


1 Answers

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.

like image 56
Gert Arnold Avatar answered Nov 21 '25 17:11

Gert Arnold