【问题标题】:passing unique identifier as parameter to the SQL Query function将唯一标识符作为参数传递给 SQL 查询函数
【发布时间】:2015-04-13 20:56:01
【问题描述】:

这是我的“SQL”查询,必须将“UserId”作为唯一标识符传递给查询中的“where”子句。

SELECT aspnet_Roles.RoleName, aspnet_Roles.Description
FROM aspnet_Roles INNER JOIN
     aspnet_UsersInRoles ON aspnet_Roles.RoleId =  aspnet_UsersInRoles.RoleId INNER JOIN
     aspnet_Users ON aspnet_UsersInRoles.UserId = aspnet_Users.UserId
WHERE (aspnet_Users.UserId = @param)

而我要传递参数的 C# 代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlTypes;

public partial class Forms_RolesMgt_RoleList_Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {

    if (!this.IsPostBack)
    {
        DSRolesTableAdapters.aspnet_RoleUsersTableAdapter userRoleAdapter = new DSRolesTableAdapters.aspnet_RoleUsersTableAdapter();
        DataTable dt = new DataTable();
        Guid user = Guid.NewGuid();
        user = Guid.Parse(Session["UserId"] as string);
        Response.Write(user);
        dt = userRoleAdapter.GetDataByUserId(user);//At this line i am passing the parameter and getting the error
        UserRolesGrdView.DataSource = dt;
        UserRolesGrdView.DataBind(); 
    }
  }
}

运行时出错:无法启用约束。一行或多行包含违反非空、唯一或外键约束的值。

通过查询预览数据时.xsd文件中的错误是:无法将参数值字符串转换为Guid

我哪里错了?

【问题讨论】:

  • Failed to covert parameter value string to Guid。您如何将参数传递给 Sql 命令?也添加该代码
  • 你能把GetDataByUserId函数的代码显示一下吗?
  • GetDataByUserId 就是上面提到的sql查询@Sachin
  • 您的代码中可能会有名为GetDataByUserId 的c# 函数。我想查看代码而不是查询。我想看看你是如何将参数@param 传递给查询的。
  • 看来您已经在这里问过这个问题并接受了解决方案。 forums.asp.net/t/….

标签: c# sql-server


【解决方案1】:

在你的情况下,你应该使用存储过程

CREATE PROCEDURE [dbo].[Name]  
(@param uniqueidentifier
)
AS 
BEGIN
    SELECT aspnet_Roles.RoleName, aspnet_Roles.Description
    FROM aspnet_Roles INNER JOIN
    aspnet_UsersInRoles ON aspnet_Roles.RoleId = aspnet_UsersInRoles.RoleId INNER JOIN
    aspnet_Users ON aspnet_UsersInRoles.UserId = aspnet_Users.UserId
    WHERE (aspnet_Users.UserId = @param)
END

并在 GetDataByUserId() 方法中为 sp 添加参数为:

command.Parameters.Add("@param",SqlDbType.UniqueIdentifier).Value=userId;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2013-08-02
    • 2015-04-25
    相关资源
    最近更新 更多