解析sql中的整数字段

时间:2013-01-14 13:15:39

标签: sql sql-server-2008 crystal-reports

我想分割sql表中整数字段中的每个数字。例如: financialNb = 7869 我需要7作为第一个数字,8作为第二个,6作为第三个,9作为第四个。这是必要的,因为我希望每个数字都用作水晶报告中的1个数据字段?

3 个答案:

答案 0 :(得分:1)

首先,您必须先将数字转换或转换为文本,然后才能以这种方式操作它们。您要查找的功能是CAST()SUBSTRING()。要使数字从右侧开始,您可以使用REVERSE()

试试这个例子:

SELECT 7869 AS field1
INTO #tmp

SELECT   SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),8,1) AS [Column8]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),7,1) AS [Column7]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),6,1) AS [Column6]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),5,1) AS [Column5]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),4,1) AS [Column4]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),3,1) AS [Column3]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),2,1) AS [Column2]
    ,SUBSTRING(REVERSE(CAST(field1 AS VARCHAR(255))),1,1) AS [Column1]
FROM #tmp

DROP TABLE #tmp

答案 1 :(得分:0)

大概你的问题是解析7869。使用substring函数:

select substring(cast(<col> as char(4)), 1, 1) as FirstChar,
       substring(cast(<col> as char(4)), 2, 1) as SecondChar,
       substring(cast(<col> as char(4)), 3, 1) as ThirdChar,
       substring(cast(<col> as char(4)), 4, 1) as FourthChar
from YourTable

我可能会错误地解释数字的排序,这假设字符串总是4位数,并且您想要字符。另一种方法是将其视为数字:

select <col%10 as FirstNum,
       (col/10) %10 as SecondNum,
       (col/100)%10 as ThirdNum,
       (col/1000)%10 as FourthNum

答案 2 :(得分:0)

您可以使用模运算符(%)来获取整数的数字,而不使用较慢的字符串操作函数,例如

select 
  value % 100000000 / 10000000,
  value % 10000000 / 1000000,
  value % 1000000 / 100000,
  value % 100000 / 10000,
  value % 10000 / 1000,
  value % 1000 / 100,
  value % 100 / 10,
  value % 10
from testData

这是一个SQL Fiddle。 如果该字段总是4个数字长,您可以逃脱:

select 
  value / 1000 as Thousands,
  value % 1000 / 100 as Hundreds,
  value % 100 / 10 as Tens,
  value % 10 as Units
from testData

但是,如果您需要在任意数字上使用它,您可以创建一个用户定义的表值函数,它将返回表中的数字,如下所示:

create function dbo.getDigits(@Input int)
returns @Digits table
(
    Digit int,
    Position int
)
as begin
  declare @pos int
  declare @digit int
  set @pos = 0

  if @input = 0
  begin
    -- zero is just a single zero digit at position 1
    insert into @digits values (0,1)
    return
  end

  while @input<>0 begin
    set @pos=@pos+1
    set @digit = @input % 10
    set @input = @input / 10
    insert into @digits values (@digit, @pos)
  end
  return
end

并像这样使用它:

SELECT td.ID, td.Value, d.Digit, d.Position 
FROM   testData td
    CROSS APPLY dbo.getDigits(td.Value) AS d
order by td.ID, d.Position Desc

(此处&#39;另一个SQL Fiddle,基于前一个)