我剛剛學習SQL並遇到了一些困難。我的數據表看起來像這樣根據用戶輸入獲取SQL中的所有記錄
DBO DATA
Id | Name | Surname | Title | Location
----------------------------------------
1 | xxx | abc | def | London
2 | xxx | abc | def | Oslo
3 | xxx | abc | def | New York
現在我想的ID,姓名,職務和姓氏,我使用這樣的查詢:
SELECT
Id, Name, Surname, Title
FROM
DATA
WHERE
Location = 'London' -- (this is user input)
,但我得到問題如果用戶輸入All
或World
或WHERE
子句中的空字符串,我希望查詢返回所有行。是否有可能通過編寫另一個查詢來處理上述特殊情況?
我使用ASP.net像這樣
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MainConnectionString %>"
SelectCommand="SELECT [Name], [Id], [Surname], [Title] FROM [DATA] WHERE [Location] = @Location)" >
<SelectParameters>
<asp:ControlParameter ControlID="Label1" Name="Location"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>`
輸入URL依賴的途徑路徑上的數據源localhost:56789/People/London/
相應的VB文件
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If (Request.PathInfo.Length = 0) Then
Else
Dim t = Request.PathInfo.Substring(1)
Label1.Text = t
End If
End Sub
我知道我可以做這個應用程序端,但我只是好奇,如果這可能在查詢本身。
這應該可能是應用程序端。 – Scotch 2013-05-04 19:54:14
你從哪裏調用這個SQL? @Scotch是正確的,這應該在你的應用程序中完成,而不是在你的數據庫中完成。 – cyroxx 2013-05-04 19:55:09
另外,不要信任用戶輸入。這可能會導致不必要的結果:http://xkcd.com/327/準備好的語句通常是解決此問題的方法。 – cyroxx 2013-05-04 19:57:19