将SQL语句组合成一个带有大小写条件的插入

时间:2016-10-06 19:04:05

标签: sql sql-server tsql

我已经找到了从这个数据库上的其他表中创建派生表所需的逻辑。但我不确定如何正确组合语句以达到预期的效果。基本上我在一些标准上移动3列,第4列我在派生表上解析为两列。

我试图解决逻辑以使这个查询有效但我对如何构建它有点迷失。

INSERT INTO table (Col1, Col2, Col3, Col4, Col5)
SELECT
r.col1,
r.col2,
r.col3,

(case 
when FirstBackslashPos > 0 and FirstUnderscorePos > 0
then substring(ParseValue,FirstBackslashPos+1,FirstUnderscorePos-FirstBackslashPos-1) 
end ) as Col4,

(case 
when FirstUnderscorePos > 0 and SecondBackslashPos > 0 
then substring(ParseValue,FirstUnderscorePos+1,SecondBackslashPos-FirstUnderscorePos-1) 
end) as Col5

FROM (
  select 
   r.ThisValue as ParseValue, 
  charindex('\',ThisValue ) as FirstBackslashPos,
  charindex('_',ThisValue  , charindex('_',ThisValue)+1) asFirstUnderscorePos,
  charindex('\',ThisValue,charindex('\',ThisValue)+1) as SecondBackslashPos
from sometable r Where somecolumn1 = 'SomeValue%')

GO

所有内容都来自同一个表格,我从中获取此数据。只是不确定如何构造它以便可以通过子案例陈述找到charindexes。

2 个答案:

答案 0 :(得分:1)

您可以使用CROSS APPLY对数据集的所有行执行相同的功能,并在语句的常用区域中提供结果。

INSERT INTO table (Col1, Col2, Col3, Col4, Col5)

SELECT
    r.col1,
    r.col2,
    r.col3,

    case 
        when ca.FirstBackslashPos > 0 and ca.FirstUnderscorePos > 0
        then substring(r.ThisValue,ca.FirstBackslashPos+1,ca.FirstUnderscorePos-ca.FirstBackslashPos-1) 
    end as Col4,

    case 
        when ca.FirstUnderscorePos > 0 and ca.SecondBackslashPos > 0 
        then substring(r.ThisValue,ca.FirstUnderscorePos+1,ca.SecondBackslashPos-ca.FirstUnderscorePos-1) 
    end as Col5

FROM sometable r

CROSS APPLY (
    select 
        charindex('\',r.ThisValue ) as FirstBackslashPos,
        charindex('_',r.ThisValue,charindex('_',r.ThisValue)+1) as FirstUnderscorePos,
        charindex('\',r.ThisValue,charindex('\',r.ThisValue)+1) as SecondBackslashPos
    ) ca

WHERE r.somecolumn1 = 'SomeValue%';

GO

答案 1 :(得分:0)

你非常接近,你计算FirstUnderscorePos的方式是错误的。

使用此样本数据:

USE tempdb
Go

CREATE TABLE dbo.SomeTable (ThisValue varchar(1000));
INSERT dbo.SomeTable
VALUES ('fistRecord\1st_monkey\xxx'), ('second\2_xxx\zzz'), ('fruit\orange_orange\apple');

您的查询应该如下所示(我只是使用col1,col2和col3的虚拟值):

SELECT col1 = 'xxx', col2 = 'xxx', col3 = 'xxx', --ParseValue,
case 
when FirstBackslashPos > 0 and FirstUnderscorePos > 0
then substring(ParseValue,FirstBackslashPos+1,FirstUnderscorePos FirstBackslashPos-1) 
end 
as Col4
case 
when FirstUnderscorePos > 0 and SecondBackslashPos > 0 
then substring(ParseValue,FirstUnderscorePos+1,SecondBackslashPos-    FirstUnderscorePos-1) 
end as Col5
FROM 
(
  select 
     r.ThisValue as ParseValue, 
     charindex('\',ThisValue ) as FirstBackslashPos,
     charindex('_',ThisValue ) as FirstUnderscorePos,
     charindex('\',ThisValue,charindex('\',ThisValue)+1) as SecondBackslashPos
  from dbo.SomeTable r 
) x;