请您帮我解释一下这句话,我试图使用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
值。
答案 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
语句中与列名对应的位置。