在' IN'中使用CSV字符串值动态SQL的子句

时间:2015-08-04 11:26:12

标签: sql sql-server

我有一个存储过程,它接受csv字符串作为参数,例如。 (' IN \ libin.jose,IN \ Pallabi.P&#39)。存储过程包含一些动态sql,它在IN子句中使用此参数,例如:(AND u1.UserName IN(' + @UserNames +'))。由于这是在动态sql中,因此条件不会在没有为CSV值添加额外单引号的情况下通过,例如(''' IN \ libin.jose'', '' IN \ Pallabi.P''&#39)



--exec [GetUwParameterDetails] 'IN\libin.jose,IN\Pallabi.P' , 'false'
ALTER PROCEDURE [dbo].[GetUwParameterDetails]

@UserNames nvarchar(max),
@IncludeInactiveusers bit

AS
BEGIN

declare @selectedUsers nvarchar(max)
--set @selectedUsers = '''IN\libin.jose ''	,''IN\Pallabi.P''';
set @selectedUsers = 'IN\libin.jose,IN\Pallabi.P';
declare @selectedPermissions nvarchar(max)
set @selectedPermissions = '''Underwrite'',''ManageUwTeamPipeline''';

DECLARE @parameterQuery1 AS NVARCHAR(MAX);



set @parameterQuery1 = '

;WITH cte_users
AS (
	SELECT users.id
		,users.UserName
		,users.FirstName
		,users.lastname
		,users.Email
		,users.E3UserName	
		,UserStatus.[Status]
		,Widgets.[Description] DefaultWidget
	FROM users 
	INNER JOIN userparametervalues upv ON users.id = upv.userid
	INNER JOIN Parameters p on upv.ParameterId = p.id 
		AND p.Name = ''UwHierarchy''
	INNER JOIN UserPermissions up ON users.id = up.userid
	INNER JOIN [Permissions] ps on up.PermissionId = ps.Id 
		AND ps.IsActive = 1 AND ps.Name IN ('+ @selectedPermissions +')
	INNER JOIN users AS u1 ON upv.value = u1.id
		AND u1.UserName IN (' + @UserNames + ')	
    INNER JOIN UserStatus ON users.StatusId = UserStatus.Id
	LEFT JOIN Widgets ON users.WidgetId = Widgets.Id )select * from cte_users ';
	exec @parameterQuery1

	END




我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

在BEGIN

之后使用此功能
set @UserNames =''''+replace(@usernames,',',''',''')+''''