我正在尝试编写一个查询,该查询将从关联表中获取设备记录及其关联数据。我的查询如下:
select e.Name,ec.Name as EquipmentClassName, s.Name as SiteName
from equipment e
left join site s on (e.SiteID = s.ID or e.SiteID is NULL and s.ID is NULL)
left join equipmentclass ec on e.EquipmentClassID=ec.ID
where e.id like '%' and (
(isNull(e.Name) OR e.Name= CASE WHEN COALESCE('','') = '' THEN e.Name ELSE '' END)
and (isNull(e.EquipmentClassID) OR e.EquipmentClassID= CASE WHEN COALESCE('1','') = '' THEN e.EquipmentClassID ELSE '' END)
and (isNull(e.SiteID) OR e.SiteID= CASE WHEN COALESCE('','') = '' THEN e.SiteID ELSE '' END)
)
好的,当我没有在where子句中传递任何参数时,我也获得包括空记录在内的所有记录。 但是当我传递任何参数时,我再次获得所有记录。我期待的是过滤后的数据。
假设我有两条记录 Equip1,class1,null和Equi2,null,Site2
现在我在传递Class1的where子句中,所以我应该得到一条包含class1而不是两条记录的记录。
我该怎么做?
答案 0 :(得分:1)
CREATE PROCEDURE equipmentData
@Name varchar(90) = null,
@EquipmentClassID varchar(90) = null,
@LocationID varchar(90) = null,
@ParentEquipmentID varchar(90) = null,
@EquipmentLevelID varchar(90) = null,
@SiteID varchar(90) = null
AS
BEGIN
select e.ID,
e.Name,
ec.Name as EquipmentClassName,
loc.Name as LocationName,
pe.Name as ParentEquipmentName ,
eql.Name as EquipmentLevelName,
s.Name as SiteName,
ep.ID as EquipmentPropertyID,
ep.Name as EquipmentPropertyName,
ep.Description as EquipmentPropertyDesc,
ep.Mandatory,
ep.SeqNbr,
ep.DataType,
ep.RuleIDs,
ep.DefaultValue,
ep.UOM,
epv.Value
from equipment e
inner join equipmentclass ec on e.EquipmentClassID=ec.ID
left join site s on (e.SiteID = s.ID or e.SiteID is NULL and s.ID is NULL)
left join location loc on e.LocationID=loc.ID
left join equipment pe on pe.ID=e.ParentEquipmentID
left join equipmentlevel eql on eql.ID = e.EquipmentLevelID
left join extendedproperty ep on ep.ObjectTypeID = e.ObjectTypeID
left join extendedpropertyvalue epv on epv.InstanceID = e.ID
where
e.id like '%'
AND (e.Name = @Name or isnull(e.Name,'')= '')
AND (@EquipmentClassID = @EquipmentClassID or isnull(e.EquipmentClassID,'')= '')
AND (@LocationID = @LocationID or isnull(e.LocationID,'')= '')
AND (@ParentEquipmentID = @ParentEquipmentID or isnull(e.ParentEquipmentID,'')= '')
AND (@EquipmentLevelID = @EquipmentLevelID or isnull(e.EquipmentLevelID,'')= '')
AND (@SiteID = @SiteID or isnull(e.SiteID,'')= '')
END
EXEC equipmentData @Name='',@EquipmentClassID='',
@LocationID='',@ParentEquipmentID='',@EquipmentLevelID='',@SiteID=''
首先复制除最后一行之外的上述代码,即
EXEC equipmentData @Name='',@EquipmentClassID='',
@LocationID='',@ParentEquipmentID='',@EquipmentLevelID='',@SiteID=''
然后按F5然后根据需要在单引号中传递参数来运行最后一行代码。您将获得数据。