Thursday, March 8, 2012

Conditional input params to SP

I've got a pretty straightforward search/results suite with several possible search parameters on the search page. I've been using an inline SQL server query with logic on the results page as shown below. How do I convert this kind of conditional logic to a stored procedure?

Dim strWhere
strWhere = " WHERE dbo.""User"".UID IS NOT NULL "

If Not request.querystring("EmployerID") = "" Then
strWhere = strWhere & " AND dbo.""User"".EmployerID = '" & replace(request.querystring("EmployerID"),"'","''") & "'"
End If

If Not request.querystring("AccountNumber") = "" Then
strWhere = strWhere & " AND dbo.""User"".AccountNumber = '" & replace(request.querystring("AccountNumber"),"'","''") & "'"
End If

If Not request.querystring("LastName") = "" Then
strWhere = strWhere & " AND dbo.""User"".LastName = '" & replace(request.querystring("LastName"),"'","''") & "'"
End If

If Not request.querystring("FirstName") = "" Then
strWhere = strWhere & " AND dbo.""User"".FirstName = '" & replace(request.querystring("FirstName"),"'","''") & "'"
End If

DBConn = New OleDbConnection(ConfigurationSettings.AppSettings("ConnStr"))
DBCommand = New OleDbDataAdapter _
("SELECT dbo.""User"".*, Convert(varchar(16), dbo.""User"".DateEntered, 101) AS Created, dbo.Employer.CompanyName, dbo.AccessLevel.AccessLevel AS AccessLevelName FROM dbo.""User"" INNER Join dbo.Employer ON dbo.""User"".EmployerID = dbo.Employer.EmployerID INNER JOIN dbo.AccessLevel ON dbo.""User"".AccessLevel = dbo.AccessLevel.AccessLevelID " & strWhere & " ORDER BY " & strSortField,DBConn)

Thanks in advance?Here is a pretty complete, though somewhat dated, overview on doing what you are looking to do (in this case inside a stored procedure, but you could do the same with a parameterized query, I expect).

What you are doing is succeptable to SQL Injection attacks, and a number of other potential problems...|||Thanks much. Great article, just what I was looking for.

I'll be coding with SQL Injection in mind as well...|||example of how i go about optional inputs

create procedure myprocedure
@.field1 type = null,
@.field2 type = null,
@.field3 type = null

as

select * from mytable where field1 = isnull(@.field1, field1)
and field2 = isnull(@.field2, field2)
and field3 = isnull(@.field3, field3)

this could be taxing on a table with a lot of entries, but for small tables this works out well and keeps me from having to write multiple sprocs for different parms

No comments:

Post a Comment