本人在使用數據庫發現一個查詢問題,請各位高手幫忙解決:
例如,我有一個表(Test),裡面只有一個字符型nvarchar字段(Ptext),字段值如下:-AM001
-AM020
-AM030
-ZM200
-ZM300
AM100
AM101
ZM100
ZM200
ZM201
我現在需要查詢范圍為 -AM001 至 -ZM200 的記錄,查詢語句如下:
SELECT *  FROM Test  WHERE (Ptxt >= '-AM001') AND (Ptxt <= '-ZM200')
但是它顯示結果為:(8條記錄)
-AM001
-AM020
-AM030
-ZM200
AM100
AM101
ZM100
ZM200
但是正確的結果應該是:(4條記錄)
-AM001
-AM020
-AM030
-ZM200
為什麼SQL 2005將不帶-號的顯示出來了呢?有什麼辦法可以查詢到我想要的正確結果(4條記錄)SQL 2005查詢問題

解决方案 »

  1.   


    create table #tb(col nvarchar(20))
    insert into #tb
    select '-AM001'
    union all select '-AM020'
    union all select '-AM030'
    union all select '-ZM200'
    union all select '-ZM300'
    union all select 'AM100'
    union all select 'AM101'
    union all select 'ZM100'
    union all select 'ZM200'
    union all select 'ZM201'
    select * from #tb
    where col like '-%' and col between '-AM001' and '-ZM200'/*
    -AM001
    -AM020
    -AM030
    -ZM200*/
      

  2.   

    create table #tb(col nvarchar(20))
    insert into #tb
    select '-AM001'
    union all select '-AM020'
    union all select '-AM030'
    union all select '-ZM200'
    union all select '-ZM300'
    union all select 'AM100'
    union all select 'AM101'
    union all select 'ZM100'
    union all select 'ZM200'
    union all select 'ZM201'
      SELECT *
     FROM #tb
     WHERE col between '-AM001' and '-ZM200' collate Chinese_PRC_BIN