I am working on a project where I need to create a dynamic web page consist of a table which column structure and data depends on a stored procedure select result.
Here is examples of a stored procedure to use:
CREATE PROCEDURE dbo.usp_CustomerView
@Address VARCHAR(1000)
AS
SELECT *
FROM Customer
WHERE CustomerAddress LIKE '%' + @Address + '%'
This procedure is working when user filter address column in the table.
The problem is, this procedure is static. If I want to filter other fields like CustomerName or CustomerPhone, I need to create another parameter and remake the procedure like this.
CREATE PROCEDURE dbo.usp_CustomerView
@Address VARCHAR(1000),
@Name VARCHAR(1000),
@Phone VARCHAR(1000)
AS
SELECT *
FROM Customer
WHERE CustomerAddress LIKE '%' + @Address + '%'
AND CustomerName LIKE '%' + @Name + '%'
AND CustomerPhone LIKE '%' + @Phone + '%'
I am trying to create a dynamic procedure to execute a dynamic SQL query based on string filter like this.
CREATE PROCEDURE dbo.usp_CustomerView
@Filter VARCHAR(MAX)
AS
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT * FROM Customer WHERE ' + @Filter
EXEC @sql
And then dynamically generate a string filter from my website like this.
Dim filterString As String = ""
For Each filter As DataFilter In e.Filter 'Here Filter give Array of filtered user input
If Not String.IsNullOrEmpty(filterString) Then filterString &= " AND "
filterString &= filter.Property & " = '" & filter.Value & "'"
Next
Command.CommandText = "usp_CustomerView @Filter"
Command.Parameters.AddWithValue("@Filter", filterString)
'Read Return Value from Command
This is working but I am concern with the security because it can easily injected. Anyone ever tried to create a dynamic where clause like this with a good security? I think this is a common things to do. But I can't find any clue.
Any suggestion?
More explanatios:
The implementation of this is actually more complex. I want to make a dynamic web page where I only set a string name of a stored procedure in database and that page will automatically generate a html table with the structure is obtained from executing the stored procedure. So I can't put any static query in the page.
AND X = @X_PARAMand simply provide a value for@X_PARAM.