我在MSSQL 2008中有一个查询,如:
IF OBJECT_Id('tempdb..#AccessibleFacilities') IS NOT NULL DROP TABLE #AccessibleFacilities
SELECT u.Userid
, AccesibleFacilityIds = dbo.GetCommaDelimitedString(upf.Facility_Id)
INTO #AccessibleFacilities
FROM Users u
INNER join UserProfileFacilities upf on upf.UserProfile_Id = up.Id
WHERE LOWER(u.Userid) = LOWER(@userId)
GROUP BY u.Userid
此查询返回",1,2,3,4,5,6,"
之类的AccessibleFacilityIds。请注意,我无法修改GetCommaDelimitedString函数。
我实际需要做的是使用这些设施ID来达到如下所示:
INSERT INTO #AccessibleProvs
SELECT Userid = @userId
, AccessibleProvIds = dbo.GetCommaDelimitedString(distinct p.Id)
FROM Provs p
inner join ProvFacs pf on p.Id = pf.Provider_Id
WHERE pf.Facility_Id in
(select a.AccesibleFacilityIds from #AccessibleFacilities a)
然而,它给我一个错误:
转换nvarchar值时转换失败',1,2,3,4,5,6,' 数据类型int。
我尝试在开头和结尾删除逗号标记,如下所示修复它,但它没有帮助:
...
where pf.Facility_Id in (
select SUBSTRING(a.AccesibleFacilityIds,2,LEN(a.AccesibleFacilityIds)-2)
from #AccessibleFacilities a
)
任何建议都将不胜感激。感谢。
答案 0 :(得分:0)
为什么不将它作为临时表中的可用列保存,而不是将Facility_Id
转换为逗号分隔的字符串?
if object_Id('tempdb..#AccessibleFacilities') is not null drop table #AccessibleFacilities;
select
u.UserId
, upf.Facility_Id
into #AccessibleFacilities
from Users u
inner join UserProfileFacilities upf
on upf.UserProfile_Id = up.Id
然后像使用in()
或exists()
一样使用它:
insert into #AccessibleProvs
select
UserId = @userId
, AccessibleProvIds = dbo.GetCommaDelimitedString(distinct p.Id)
from Provs p
inner join ProvFacs pf
on p.Id = pf.Provider_Id
where exists (
select 1
from #AccessibleFacilities a
where a.Facility_Id = pf.Facility_Id
--and a.UserId = @UserId -- Do you need to check Facility_Id by User?
)
如果您在开头有@UserId
的值,则可以将临时表使用限制为您需要的用户。希望这段代码不适用于某种游标或其他循环。