2011-12-31 70 views
1

我对下面的查询的输出不解的查询:需要帮助理解涉及“案”,“选择进入”条款

select 
    'Eq Type' = 
    case 
    when 
     substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) = 
     substring([Eq Type], charindex('-', [Eq Type]) + 1, len([Eq Type])) 
    then 
     substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) 
    when 
     substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) <> 
     substring([Eq Type], charindex('-', [Eq Type]) + 1, len([Eq Type])) 
    then 
     replace([Eq Type], '-', '') 
    else 
     null 
    end, 
    'Failure_Class' = 
    case 
    when charindex('-', [Eq Type]) <> 0 and 
     (substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) = 
     substring([Eq Type], charindex('-', [Eq Type]) + 1, len([Eq Type]))) 
    then 
     substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) 
    when charindex('-', [Eq Type]) <> 0 and 
     (substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) <> 
     substring([Eq Type], charindex('-', [Eq Type]) + 1, len([Eq Type]))) 
    then 
     substring([Eq Type], 1, charindex('-', [Eq Type]) - 1) + 
     '\' + 
     replace([Eq Type], '-', '') 
    when CHARINDEX('-', [Eq Type]) = 0 
    then 
     Failure_Class 
    else 
     null 
    end 
from dbo.Location 
  1. 位置表包含了25385条记录,但只有8157记录回。为什么记录被过滤掉?

  2. 当我尝试将dbo.ModifiedLocation添加到上述查询中时,它失败,并显示以下错误:“传递给LEFT或SUBSTRING函数的长度参数无效”。该消息非常具有描述性,但为何在添加into子句时引发此错误?为什么查询在没有into子句的情况下正常执行?

编辑 我想解释什么,我想要的目的。原始数据集有两个我感兴趣的列,Eq Type和Failure_Class。数据如下:

Eq Type, Failure_Class 
ACCU-ACCU, ACCU 
AUX-AUX, AUX 
VA-BA, VA 
VA-CH, VA 
IP-LS, IP 
null, null 
VE, VE 
JB, JB 
VA, null 

由于数据是由人工维护的,因此不一致。我需要以下格式的数据,以便能够将其导入到他们的资产管理系统中。

Eq Type, Failure_Class 
ACCU, ACCU 
AUX, AUX 
VABA, VA\VABA 
VACH, VA\VACH 
IPLS, IP\IPLS 
null, null 
VE, VE 
JB, JB 
VA, VA 

编辑2 看来,我已经找到了问题。我在免费版Toad 5.6 for SQL Server中运行这个查询。当我切换到SSMS并删除“进入dbo.ModifiedLocation”时,查询引发了熟悉的“传递给LEFT或SUBSTRING函数的无效长度参数”错误。这回答了我的第二个问题。我猜如果我解决这个错误,我会得到所需的输出。感谢您的帮助。

+1

您可以发布dbo.Location中的数据或数据样本,以及在运行语句时获得的结果以允许某人提供帮助 – 2011-12-31 00:57:43

+0

@Trevor Done。希望能够澄清我正在努力完成的事情。 – 2011-12-31 01:32:04

回答

3

要插入到现有的表,你需要INSERT INTO dbo.ModifiedLocation SELECT ...

SELECT ... INTO dbo.ModifiedLocation FROM ...语法是创建表以及插入它。


而对于返回记录的数量。除非您有JOIN,WHERE子句或GROUP BY或DISTINCT,否则这应该返回与源表中存在的记录数完全相同的记录数。

这正是您正在运行的查询吗?

+0

是的,这正是我正在运行的查询。我想创建一个新表ModifiedLocation并将修改后的数据插入到它。这是一个ETL练习,但我无法访问SQL Server集成服务,这就是我“手工”操作的原因。 – 2011-12-31 01:10:36