SQL Server:在条件中以逗号传递公司ID(int)

时间:2018-07-06 08:05:49

标签: sql sql-server

我正在使用SQL Server2008。在where条件下遇到问题,将多个用逗号(,)分隔的公司ID值传递给Int公司ID。

ALTER Procedure
  [dbo].[SP_WorkOrderDetails] @CompanyID varchar(50)
as begin
  Select
    *
  from
    ClientContract C
  left join
    WorkOrder W
  on
    C.Id=W.ClientContractId
  left join
    ClientContractContacts CB
  on
    CB.ClientContractld=C.Id
  left join
    Client CL
  on
    CL.Id= C.Clientld
  left join
    Client CN
  on
    CN.Id= CB.Contactld
  left join
    BaseUnit B
  on
    B.Id=W.BaseUnitId
  left join
    users u
  on
    u.Staffld = W.AssignedTo
  left join
    LatticeERP_DFS..sv_App_Staff SPT
  on
    SPT.Leaderld=W.AssignedTo and
    SPT.Module = 'S'
  left join
    Staff SS
  on
    SS.Id=u.StaffId --and ss.IsTeamLeader = 1
  left join
    Companies Comp
  on
    Comp.id=C.Companyld
  Where
    convert(nvarchar(50),isnull(C.companyID, 1)) in (replace('1,7', '''', ','))
  Order By
    ContractCode,
    WorkOrderNo Desc
end 

2 个答案:

答案 0 :(得分:0)

你可以试试吗

IN  (select cast ( STRING_SPLIT ( '1,7'  , ',' )  as int ) )

或者可能是

 IN  ( SELECT 
 Split.a.value('.', 'VARCHAR(100)') AS CVS  
 FROM  
(
SELECT CAST ('<M>' + REPLACE('1,7', ',', '</M><M>') + '</M>' AS XML) AS CVS 
) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a) )

答案 1 :(得分:0)

您可以使用此表值函数:

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
create FUNCTION dbo.SplitString(@str VARCHAR(4000),@seprator VARCHAR(1))
RETURNS TABLE
AS
RETURN ( WITH tokens(p,a,b) AS (SELECT 1,1,CHARINDEX(@seprator,@str)
UNION ALL SELECT p+1,b+1,CHARINDEX(@seprator,@str,b+1)
FROM tokens WHERE b>0
)
SELECT
SUBSTRING(@str,a,CASE WHEN b > 0 THEN b-a ELSE 4000 end)
AS VALUE
FROM tokens)

GO

使用方式:

... where ID In(select value from dbo.SplitString('1,7,...',','))