2012-08-08 80 views
0

在一個表中我有一個入口與SQL服務器空間

12-345678 
123-456-789 
123456789 

在UI的文本框,當有人類型的搜索:  - (two spaces then one dash).

輸出應該是:

12-345678 

在UI文本框,當有人類型時:12-

輸出應爲:

12-345678

在UI的文本框,當有人類型:12

12-345678 
123-456-789 
123456789 

我選擇查詢要做到這一點的

select column1,column2 from table1 where column1 like '%textbox1.text%'; 

textbox1.text->文本框的名字UI。需要返回,爲前 -

任何事情之前:

if you type 12-, return output should be 12-345678 alone, 
if you type 123-, then the return output should be 123-456-789 alone. 
if you type - (only dash, no space on the front , then the return output should be 12-345678 and 123-456-789 . 

然而,在一些條件下發生故障,有沒有什麼辦法可以計算出空間和SQL直接修改查詢?

+0

你說兩個空格和破折號建議立即進行刪除返回12-345678,因爲它是唯一一個在3號字符是幾許? – 2012-08-08 21:39:37

+0

之前的任何事情 - 需要返回,例如:如果您鍵入12-,則返回輸出應該是12-345678,如果您鍵入123-,則返回輸出應該是123-456-789。 – Sharpeye500 2012-08-08 21:41:04

回答

1

如果我理解正確:當有前導空格時,需要將它們轉換爲_。對於沒有前導空格的情況,您可以追加%

<space><space>- '__-%' 
12-    '12-%' 
12    '12%' 
123-    '123-%' 

但是這一個不適合的模式,所以這是一個特殊情況:

-    '%-%' 

你想要一個行修復我懷疑,不過雖然你很可能這一切包成單iff(),如果可能,我會避免。

編輯補充

C#:

string arg = theTextbox.Text; 
arg = arg.Replace("'", "''"); // avoid SQL injection attack 

arg = arg.Replace(" ", "_"); // space = single character wildcard = '_' 

if (arg.StartsWith("-")) // special case 
    arg = "%-"; 

string sqlStatement = string.Format("SELECT column1, column2 " + 
      "FROM table1 WHERE column1 like '{0}%', arg); 
+0

謝謝,我會確定之前的空間 - 在SQL中? – Sharpeye500 2012-08-08 22:00:18

+0

你是否從其他語言調用SQL? – egrunin 2012-08-08 22:11:30

+0

我本來應該使用sql,但我需要在C#中進行驗證(計算空間)。 – Sharpeye500 2012-08-08 22:19:10

2

喜歡的東西

"Select column1,column2 From Table1 Where column like " + textbox1.text.Replace(' ','_') + "%" 

「CEPT你應該使用過程中的參數化查詢。

SQL通配符字符是

% 0 to n of any character 
underscore 1 single character 
[xyz] any single character that is x, y or z 

所以在你的榜樣它貴方覺得像「__-%」 2 folowed的空間會像「_2%」,拿起所有三個你的例子因爲每個人都是一個字符後跟「2」,其次是其他東西