【问题标题】:Using Select statement for Insert Statement Value使用 Select 语句插入语句值
【发布时间】:2014-12-25 06:23:21
【问题描述】:

你能帮我解决这个问题吗,我正在尝试使用 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 值。

【问题讨论】:

标签: c# asp.net visual-studio-2010


【解决方案1】:

插入语句应该是

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

或者SELECT TOP(1) ProfileId 以确保您永远不会获得超过 1 个值。

【讨论】:

    【解决方案2】:

    插入的 SQL 应该是:

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

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

    【讨论】:

    • 感谢您的重播,我只从 userId 中选择 ProfileId 而不是两者都选择
    • 当你像这样包含参数时,它不会从用户表中选择,而是直接在SQL中替换值。所以假设 @FriendProfileId 设置为 23,SELECT 语句实际上最终是 SELECT 23, ProfileID FROM user_profile...
    猜你喜欢
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多