1

我有一个数据库,我们的用户可以通过界面对其进行修改。对于一个字段(companyID),他们应该能够在字符串中放置一个星号作为通配符。

例如,他们可以输入 G378* 来代表以 G378 开头的任何公司 ID。

现在在我的客户程序中,我提供了一个“完整”的 companyID 作为参数:

SELECT * FROM table WHERE companyID = '" + myCompanyID + "'

但是我必须检查通配符,有什么可以添加到我的查询中来检查的。我不知道如何解释它,但它与我习惯的有点倒退。我可以修改我提供的值(完整的 companyID)以匹配查询本身中的通配符值吗?

我希望这是有道理的。

谢谢!

编辑:用户没有使用SELECT. 用户只使用INSERTUPDATE,他们是在字段中放置 * 的人。我的程序正在使用SELECT,我只有完整的 companyID(没有星号)。

4

3 回答 3

3

This is a classic SQL Injection target! You should be glad that you found it now.

Back to your problem, when users enter '*', replace it with '%', and use LIKE instead of = in your query.

For example, when end-users enter "US*123", run this query:

SELECT * FROM table WHERE companyID LIKE @companyIdTemplate

set @companyIdTemplate parameter to "US%123", and run the query.

I used .NET's @ in the example, but query parameters are denoted in ways specific to your hosting language. For example, they become ? in Java. Check any DB programming tutorial on use of parameterized queries to find out how it's done in your system.

EDIT : If you would like to perform an insert based on a wildcard that specifies records in another table, you can do an insert-from-select, like this:

INSERT INTO CompanyNotes (CompanyId, Note)
   SELECT c.companyId, @NoteText
   FROM Company c
   WHERE c.companyId LIKE 'G378%'

This will insert a record with the value of the @NoteText parameter into CompanyNotes table for each company with the ID matching "G378%".

于 2012-05-16T17:36:29.037 回答
0

This is somewhat implementation dependant and you did not mention which type of SQL you are dealing with. However, looking at MS SQL Server wildcards include % (for any number of characters) or _ (for a single character). Wildcards are only evaluated as wildcards when used with "like" and not an = comparison. But you can pass in a paramater that includes a wildcard and have it evaluated as a wildcard as long as you are using "like"

于 2012-05-16T17:36:14.407 回答
0

在 TSQL 中,我会使用 replace 和 like。IE:

select * from table where companyid like replace(mycompanyid,'*','%');
于 2012-05-16T17:38:06.097 回答