2010-02-25 64 views
4

爲什麼這些查詢返回不同的值?第一個按預期返回結果集,但第二個(就我所知,完全相同)不是。有什麼想法嗎?SQL Server變量

1:

declare @c varchar(200) 

set @c = 'columnName' 

select top 1 * 
from myTable 
where @c is not null 
     and len(convert(varchar, @c)) > 0 

2:

SELECT top 1 * 
FROM myTable 
WHERE columnName IS NOT NULL 
     and len(convert(varchar,columnName)) > 0 
+0

謝謝大家,我看到發生了什麼事。現在是後續行爲:第一個查詢返回最上一行,其中columnName的值爲8.第二個查詢不返回任何內容。 ColName = 8的第一行不應該滿足既不爲空也不滿足len> 0並且被查詢返回? – Colin 2010-02-25 20:36:24

+0

'columnName'的實際數據類型是什麼? – 2010-02-25 20:43:54

+0

這是一個nvarchar的長度爲50的 – Colin 2010-02-25 20:57:39

回答

6

這是因爲他們是不一樣的查詢 - 變量文本沒有得到聯到查詢。

在查詢1中,您正在驗證@c不是null(true,您設置了它)並且其長度大於0(true,它是10)。由於兩者都是真實的,查詢1變爲:

select top 1 * from myTable 

(它會返回基於一個合適的指數MyTable的第一行。)

編輯:上解決問題的意見。

declare @myTable table 
(
    columnName varchar(50) 
) 

insert into @myTable values ('8') 

declare @c nvarchar(50) 
set @c = 'columnName' 

select top 1 * 
from @myTable 
where @c is not null 
     and len(convert(varchar, @c)) > 0 

select top 1 * 
from @myTable 
where columnName is not null 
     and len(convert(varchar,columnName)) > 0 

現在,當我運行這兩個查詢返回相同的結果。您必須告訴我我在哪裏誤傳了您的實際數據/查詢以獲得更多幫助(或者只是在此處尋找解決方案)。

+0

+1。我認爲OP的印象是@c會替換一個真正的專欄進行搜索。 – 2010-02-25 20:27:55

2

在第一個查詢,要檢查的值「COLUMNNAME」靠在參數IS NOT NULL和長度> 0。在第二個查詢,你正在檢查在COLUMNNAME柱針對這些參數的值。

應當注意的是,查詢1將總是返回一行(假設行存在),其中查詢2將只返回一行如果COLUMNNAME的內容不爲空和長度> 0

+0

謝謝,我看到發生了什麼事。現在是後續行爲:第一個查詢返回最上一行,其中columnName的值爲8.第二個查詢不返回任何內容。 ColName = 8的第一行不應該滿足既不爲空也不滿足len> 0並且被查詢返回? – Colin 2010-02-25 20:34:10

0

他們不一樣 - 第一個檢查變量,第二個檢查列。 「where @c is not null」表示其中變量@c不是null--它不是,因爲它包含值'columnName'。 「where columnName is not null」表示其中字段columnName不包含null。和評估長度一樣。

0

第一個查詢實際的計算結果爲

select top 1 * from myTable where 'columnName' is not null and len(convert(varchar, 'columnName')) > 0 

並不像你所希望看到for.expected什麼。

0

這兩個查詢不同於第二個查詢中您正在評估字段columnname的實際值。以下是您的第一個功能的等同物。

SELECT top 1 * FROM myTable WHERE 'columnName' IS NOT NULL and len(convert(varchar,'columnName')) > 0