2011-12-31 65 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