Reputation:
I'm trying to modify a stored procedure used in an ASP.NET page.
By default, the stored procedure returns all of the data, which can be overwhelming for employees in the plant.
I want to add a drop down menu item for the column name and a text box for a value to allow our employees to search the data for their specific items.
What I would like to add is the ability to pass in a Column Name and Column Value to search, similar to the following:
DECLARE @colName nVarChar(50), @colValue nVarChar(50)
SET @colName='EmployeeID'
SET @colValue='007135'
SELECT Column1, Column2, Column3, Column4, Column5, Column6, Column7
FROM viewNum1
WHERE ((@colName IS NULL) OR (@colValue IS NULL) OR ('['+@colName+']'=@colValue))
If all values passed in (@colValue
and @colName
), all records return; however, if I try specifying that @colName
=EmployeeID and @colValue
='007135' (a value that does exist in the database), no records are returned.
Next is the problem that I am running an old SQL Server 2000 database that does not allow the stored procedure to access the table column names, and the whole technique looks prone to SQL Injection.
Finally, I don't see how to bind my GridView
control to this and still have the ability to display all records.
How would I write such a filtering stored procedure?
Upvotes: 2
Views: 1449
Reputation: 2103
I would definitely not recommend doing this with any critical database. As it opens you up to easy attacks on your data but since you asked below will do the trick for you:
DECLARE @colName nVarChar(50) = NULL;
DECLARE @colValue nVarChar(50) = NULL;
DECLARE @sql = 'SELECT Column1,Column2,Column3,Column4,Column5,Column6,Column7 FROM viewNum1 WHERE 1=1 ';
if ISNULL(@colName,'')<>'' AND ISNULL(@colValue,'')<>''
SET @sql = @sql + ' AND ' + @colName + '=''' + @colValue + '''';
exec(@sql);
I would recommend you instead create a proc with nullable parameters for each column as it is safer:
CREATE PROCEDURE dbo.ProcName
@Column1 as nvarchar(50) = NULL,
@Column[n] as [dbtype] = NULL
AS
BEGIN
SELECT Column1, Column[n]...
FROM viewNum1
WHERE
((@Column1 IS NULL) OR (Column1 = @Column1))
AND ((@Column[n] IS NULL) OR (Column[n] = @Column[n]))...
END
GO
Upvotes: 3
Reputation: 33173
You'll have to generate the entire SQL string (dynamic sql) if you pass in a column name as a parameter.
And then you use exec(SQL_STATEMENT)
to execute the sql statement. BTW I do not recommend doing this. Here is an example on the dbforums: http://www.dbforums.com/microsoft-sql-server/969925-passing-table-column-name-parameter-stored-procedure.html
Also in your code this part doesn't make much sense @colValue IS NULL
. If I am reading this correctly you are stating whether a value is NULL and it never is.
Upvotes: 1