简体   繁体   中英

How to split string with delimiter and convert to integer

hi i am writing query in sql server procedure in which i pass comma seprated nvarchar values i want to filter these value in sql server query code is given below

declare @RoleId NVARCHAR(MAX) = '1,2,3'
Declare @RoleTempId  int;
Set @RoleTempId = Cast(@RoleId As INT);
BEGIN
SELECT        dbo.RolePermission.PermissionId, dbo.Permission.PermissionName
FROM            dbo.RolePermission INNER JOIN
                         dbo.Permission ON dbo.RolePermission.PermissionId = dbo.Permission.PermissionId
WHERE        (dbo.RolePermission.RoleId IN (@RoleTempId))
END

this is giving error please guide me about this query thank you.

One simple solution for string splitting is to convert the source ( 1,2,3 ) string (which could be declared as VARCHAR and not NVARCHAR if it contains only integers) to XML ( <r>1</r><r>2</r><r>3</r> ) and then you could shredd this XML and insert every values (integer) into a table variable:

DECLARE @RoleId NVARCHAR(MAX) = '1,2,3'

DECLARE @SelectedRoles TABLE (RoleId INT PRIMARY KEY); -- No duplicates allowed

DECLARE @x XML;
SET @x = N'<r>' + REPLACE((SELECT @RoleId FOR XML PATH('')), N',', N'</r><r>') + N'</r>';
/*
@x content:
<r>1</r><r>2</r><r>3</r>
*/
INSERT  @SelectedRoles (RoleId)
SELECT  y.XmlCol.value('(.)', 'INT') AS RoleId
FROM    @x.nodes('/r') y(XmlCol);

...
WHERE        (dbo.RolePermission.RoleId IN (SELECT sr.RoleId FROM @SelectedRoles sr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM