从列中拆分sql中的字符串

时间:2013-05-06 08:24:38

标签: sql sql-server tsql

我的表格中有column,文字(字符串)如 19.5 7.14 ,但只有 19 11

我想将 2列 1中的文字与“。”之前的所有文字分开。和“。”之后的所有文本都是1。 。

对于字符串中不带 的条目,该表必须在第二列中包含 00 。此外,之后的所有数据都必须为2个字符长(填充为0)。

e.g。 19.5 必须提供column1: 19 column2: 50; 11 必须提供 column1:11 column2:00 任何人都可以帮助我使用正确的tsql代码吗?

3 个答案:

答案 0 :(得分:4)

请尝试:

select 
    YourCol, 
    SUBSTRING(YourCol, 0, CHARINDEX('.', YourCol+'.')) Col1, 
    LEFT(SUBSTRING(YourCol, CHARINDEX('.', YourCol+'.')+1, 2)+'00', 2) Col2 
from YourTable

select
    YourCol,
    CAST(YourCol AS INT) Col1,
    RIGHT(PARSENAME(YourCol,1), 2) Col2
from
(
    select 
        CONVERT(NUMERIC(18,2), YourCol) YourCol
    from YourTable
)x

样品:

declare @tbl as table(txt nvarchar(10))
insert into @tbl values ('19.5'), ('11'), ('7.14')

select 
    txt, 
    SUBSTRING(txt, 0, CHARINDEX('.', txt+'.')) Col1, 
    LEFT(SUBSTRING(txt, CHARINDEX('.', txt+'.')+1, 2)+'00', 2) Col2 
from @tbl

select
    txt,
    CAST(txt AS INT) Col1,
    RIGHT(PARSENAME(txt,1), 2) Col2
from
(
    select 
        CONVERT(NUMERIC(18,2), txt) txt
    from @tbl
)x

答案 1 :(得分:0)

select cast(cast(number as float) as int) column1,
right(cast(number as numeric(9,2)), 2) column2
from
(VALUES ('19.5'),('7.14'),('19'),('11') ) t(number)

答案 2 :(得分:0)

试试这个,

Declare @InputList VARCHAR(8000), @Delimiter VARCHAR(8000);
Declare @1stvalue nvarchar(20), @2ndValue Int;

Set @InputList = '19.5';
Set @Delimiter = '.';

set @1stvalue = (select RTRIM(LTRIM(SUBSTRING(@InputList,1,CHARINDEX(@Delimiter,@InputList,0)-1))));

set @2ndValue = (Select RTRIM(LTRIM(SUBSTRING(@InputList,CHARINDEX(@Delimiter,@InputList,0)+LEN(@Delimiter),LEN(@InputList)))) )
set @2ndValue = (select case when @2ndValue < 10 then convert (varchar(10) ,convert (varchar(10),@2ndValue) + '0') else convert (varchar(10), @2ndValue) end);

SELECT @1stvalue AS Column1, @2ndValue AS Column2;

您可以将其用作功能..