与SQL服务器空间

问题描述:

在一个表中我有一个入口与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

如果我理解正确:当有前导空格时,需要将它们转换为_。对于没有前导空格的情况,您可以追加%

<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

喜欢的东西

"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”,其次是其他东西