Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql获取数字的前2组_Sql_Sql Server_Sql Server 2008_Tsql - Fatal编程技术网

Sql获取数字的前2组

Sql获取数字的前2组,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,我的数字格式如下:123.456.789.1.2.3 我需要一个函数来检索数字的前两组并将它们放入bigint:result:123456中 到目前为止我所做的: CREATE FUNCTION bl.fn_get_2_groups ( @str nvarchar(255) ) RETURNS bigint AS BEGIN DECLARE @newStr nvarchar(255) select @newStr = SUBSTRING(@str,1,charindex('.',@str)-1

我的数字格式如下:123.456.789.1.2.3

我需要一个函数来检索数字的前两组并将它们放入bigint:result:123456中

到目前为止我所做的:

CREATE FUNCTION bl.fn_get_2_groups
(
@str nvarchar(255)
)
RETURNS bigint
AS BEGIN

DECLARE @newStr nvarchar(255)
select @newStr = SUBSTRING(@str,1,charindex('.',@str)-1),  @str =  SUBSTRING(@str,charindex('.',@str)+1,LEN(@str))
select @newStr += SUBSTRING(@str,1,charindex('.',@str)-1)   
return convert(bigint,@newStr)

END GO

有人知道另一种方法吗?也许更优雅或更短?

您的方法看起来还可以。如果您想要更优雅或更简单的东西,我认为您必须编写一个CLR函数。然后,您可以利用.NETAPI为字符串解析提供的所有功能。或者,您可以尝试在应用程序层中执行此解析。当然,这可能不可行

您可以在此处阅读有关正则表达式和CLR函数的信息:

另外,我建议修改SQLUDF,以确保输入字符串实际上有两个句点

这应该有效:

cast(REPLACE(LEFT(@str,CHARINDEX('.', @str,CHARINDEX('.', @str)+1)),'.','') as bigint)

前两个数字总是3位数,或者可以有更多/更少?Coroveiandre我使用@DasLinkedLight答案。是的!:)