c# - 使用 Select 语句插入语句值

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

你能帮我处理这个语句吗,我正在尝试使用 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 值。

最佳答案

插入语句应该是

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

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

关于c# - 使用 Select 语句插入语句值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642513/

相关文章:

c - Visual Studio 2010 问题中的链表

c# - StructureMap 解决跨项目的依赖关系

c# - wcf http 绑定(bind)与 dualhttp 绑定(bind)

asp.net - 使用 XSP/Mono 托管时,ASP .Net WebAPI 不适用于 Owin

visual-studio-2010 - 在 VS2010 中,VC++ 错误 LNK 2019 with CoolProp 5.0.0

visual-studio-2010 - 查找子类和实现

c# - 在 dynamodb 中使用 context.fromquery 查询时限制不起作用

c# - 从 AngularJS 和 ASP.net MVC 传递数据 $http.post 获取 null

javascript - 回发后在 js 中分配的隐藏值丢失

asp.net - 创建所需的 URL - 我应该循环吗?