列的最小值和最大值
创建一个函数,以通过串联字符串,将它们拆分为行然后返回正确的值来返回列的最小值和最大值
信息
这些函数将返回串联文本字符串中的最小值和最大值。
要使用它,您将需要创建需要解析的值,并且还具有TextToRows函数,因为我们会将字符串转换为行并将相关值解析回去。
最初仅适用于Integers,我们也为字符串添加了最小值和最大值。
使用字符串函数时,如果您要区分大小写,则可能需要更改排序规则并将其更改为带顺序的顶部。
SQL Code - MAX
CREATE FUNCTION [dbo].[GetStrMAX_INT](@Delim NVARCHAR(1),@Str NVARCHAR(200)) RETURNS INT AS BEGINDECLARE @RS INTSET @RS=(SELECT MAX(CONVERT(INT,REPLACE(WordStr,@Delim,'')))FROM Utilities.dbo.TextToRows(@Delim,@Str)WHERE ISNUMERIC(WordStr)=1)RETURN @RSENDGOSELECT dbo.GetStrMAX_INT(',','1,2,3,4,5,a')
SQL Code - MIN
CREATE FUNCTION [dbo].[GetStrMIN_INT](@Delim NVARCHAR(1),@Str NVARCHAR(200)) RETURNS INT AS BEGINDECLARE @RS INTSET @RS=(SELECT MIN(CONVERT(INT,REPLACE(WordStr,@Delim,'')))FROM Utilities.dbo.TextToRows(@Delim,@Str)WHERE ISNUMERIC(WordStr)=1)RETURN @RSENDGOSELECT dbo.GetStrMIN_INT(',','1,2,3,4,5,a')
We've got strings covered too...
ALTER FUNCTION [dbo].[GetStrMAX](@Delim NVARCHAR(1),@Str NVARCHAR(200)) RETURNS NVARCHAR(100) AS BEGINDECLARE @RS NVARCHAR(100)SET @RS=(SELECT MAX(CONVERT(NVARCHAR(100),REPLACE(WordStr,@Delim,'')))FROM Utilities.dbo.TextToRows(@Delim,@Str))RETURN @RSENDGOALTER FUNCTION [dbo].[GetStrMIN](@Delim NVARCHAR(1),@Str NVARCHAR(200)) RETURNS NVARCHAR(100) AS BEGINDECLARE @RS NVARCHAR(100)SET @RS=(SELECT MIN(CONVERT(NVARCHAR(100),REPLACE(WordStr,@Delim,'')))FROM Utilities.dbo.TextToRows(@Delim,@Str))RETURN @RSENDGO
Testing
SELECT dbo.GetStrMAX_INT(',','1,2,3,x,5,a') --5SELECT dbo.GetStrMIN_INT(',','1,2,3,x,5,a') --1SELECT dbo.GetStrMAX(',','1,2,3,x,5,a') --xSELECT dbo.GetStrMIN(',','1,2,3,x,5,a') --1