以下是我的表结构:

create table Department(
    deptid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Department_P_KEY PRIMARY KEY,
    departmentname varchar(100)
    )

create table Employee(
    empid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Employee_P_KEY PRIMARY KEY,
    name varchar(50),
    city varchar(50),
    deptid UNIQUEIDENTIFIER NOT NULL,
    foreign key(deptid) references Department(deptid) ON DELETE CASCADE ON UPDATE CASCADE
    )


我的问题是,当我选择多个列并在所有主键和外键都为DISTINCT的列上应用UNIQUEIDENTIFIER时,该时间查询将给出错误消息。我的查询和错误如下:

select distinct(Department.deptid),min(Employee.empid) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid


错误消息是:


  消息8117,级别16,状态1,行2操作数数据类型uniqueidentifier对min运算符无效。


但是,如果主键和外键为int,则上述查询将成功执行,因为min函数支持整数,但是如何使用uniqueidentifier键选择不同的记录。

以下是我的Nhibernate查询:-

EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.DepartmentMaster = new DepartmentEntity();
            ProjectionList projectionList = Projections.ProjectionList();
            projectionList.Add(Projections.Distinct(Projections.Property<EmployeeEntity>(x => x.DepartmentMaster)).WithAlias(() => employeeEntity.DepartmentMaster));
            projectionList.Add(Projections.Property<EmployeeEntity>(x => x.empid).WithAlias(() => employeeEntity.empid));

            IList<EmployeeEntity> query = null;
            query = NHSession.QueryOver<EmployeeEntity>()
            .Select(projectionList)
            .TransformUsing(Transformers.AliasToBean<EmployeeEntity>()).List<EmployeeEntity>();


如何按照上述sql查询先在sql中执行不同的查询?

最佳答案

只需将UniqueIdentifier转换为字符串

select distinct(Department.deptid),min(CAST(Employee.empid AS NVARCHAR(36))) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid

关于c# - 如何使用Nhibernate从连接两个具有所有ID的表的表中选择只有一个不同的列的多个列是UNIQUEIDENTIFIER,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44920144/

10-11 16:23