这个变量该怎么定义?create function [dbo].[GetUserName](@ColunmValue nvarchar(50))returns varchar(80
这个变量该怎么定义?
create function [dbo].[GetUserName](@ColunmValue nvarchar(50)) returns varchar(8000) as begin DECLARE @RetVal varchar(8000) SET @RetVal = '' select @RetVal = name + ',' + @RetVal from [Dealer] where id in (@ColunmValue) IF LEN(@RetVal) > 0 SET @RetVal = LEFT(@RetVal, LEN(@RetVal) - 1) return (@Retval) end
create function [dbo].[GetUserName](@ColunmValue nvarchar(50)) returns varchar(8000) as begin DECLARE @RetVal varchar(8000) SET @RetVal = '' select @RetVal = name + ',' + @RetVal from [Dealer] where id in (@ColunmValue) --这儿写的不对,如果你传了个"1,2,3",会把"1,2,3"转化成整型,会报错的 IF LEN(@RetVal) > 0 SET @RetVal = LEFT(@RetVal, LEN(@RetVal) - 1) return (@Retval) END go
--改成: create function [dbo].[GetUserName](@ColunmValue nvarchar(50)) returns varchar(8000) as begin DECLARE @RetVal varchar(8000) SET @RetVal = '' DECLARE @temp TABLE(NAME NVARCHAR(255)) INSERT @temp EXEC('SELECT name FROM [Dealer] where id in ('+ @ColunmValue +')') select @RetVal = name + ',' + @RetVal from @temp IF LEN(@RetVal) > 0 SET @RetVal = LEFT(@RetVal, LEN(@RetVal) - 1) return (@Retval) END
[解决办法] where id in (@ColunmValue)
要求@ColunmValue是一个记录集
而你的参数实际是'1,3,6',所以得组合为sql字符串再执行
或者改为这样: where ','+@ColunmValue+',' like '%,'+id+',%' [解决办法] 还有一种办法,写2个函数 函数1,拆分字符,返回单列的表1. 需要的参数@ColunmValue nvarchar(50) 函数2,调用函数1做条件就行。 需要的参数@ColunmValue nvarchar(50)
[解决办法]
你试一试就知道了,非常神奇 [解决办法]
where id in (@ColunmValue) 要求@ColunmValue是一个记录集
而你的参数实际是'1,3,6',所以得组合为sql字符串再执行
或者改为这样: where ','+@ColunmValue+',' like '%,'+id+',%'
这样能行?
where (','+@ColumnValue+',')like '%,'+cast (ID as varchar)+',%' [解决办法]
CREATE TABLE [Dealer] (ID INT, NAME VARCHAR(10)) INSERT Dealer SELECT 1, 'name1' UNION ALL SELECT 2, 'name2' UNION ALL SELECT 3, 'name3' UNION ALL SELECT 4, 'name4' --方法1 create function [dbo].[GetUserName](@ColunmValue nvarchar(50)) returns varchar(8000) as begin DECLARE @RetVal varchar(8000) SET @RetVal = '' select @RetVal = name + ',' + @RetVal from [Dealer] where CHARINDEX(','+LTRIM(id)+',', ','+@ColunmValue+',') > 0 IF LEN(@RetVal) > 0 SET @RetVal = LEFT(@RetVal, LEN(@RetVal) - 1) return (@Retval) END SELECT dbo.[GetUserName]('1,3,2') /*name3,name2,name1*/ go --方法2 ALTER function [dbo].[GetUserName](@ColunmValue nvarchar(50)) returns varchar(8000) as begin DECLARE @RetVal varchar(8000)
SET @RetVal = '' ;WITH cte AS ( SELECT rowid=1, string = CAST(LEFT(@ColunmValue, CHARINDEX(',', @ColunmValue + ',') - 1) AS int), Split = CAST(STUFF(@ColunmValue + ',', 1, CHARINDEX(',', @ColunmValue + ','), '') AS NVARCHAR(MAX)) UNION ALL SELECT rowid=rowid+1, string = CAST(LEFT(Split, CHARINDEX(',', Split) - 1) AS int), Split = CAST(STUFF(Split, 1, CHARINDEX(',', Split), '') AS NVARCHAR(MAX)) FROM cte WHERE Split > '' ) SELECT @RetVal = @RetVal+B.NAME+',' FROM cte a INNER JOIN [Dealer] b ON a.string = b.id OPTION (MAXRECURSION 0) --递归次数无限制 IF LEN(@RetVal) > 0 SET @RetVal = LEFT(@RetVal, LEN(@RetVal) - 1) return (@Retval) END go