Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to create a dynamic filter in sql

on the where

i want for example "ID" (>,<,>=,<=,=) @ID where these operation changed dynamically by the user as a dropdownlist in the interface

Any suggestions?

im using this as select

SQL
 @v1 varchar(50),
	   @v2 int 

DECLARE cur cursor for
SELECT abc
	FROM 
	sometable
	WHERE  
		(@lv1 IS NULL OR @v1 =@lv1) 
	AND (@lv2 IS NULL OR @v2 =@lv2) 


i want the v2 parameter to be filtered on these operators (>,<,>=,<=,=)
Posted
Updated 12-Sep-14 2:16am
v2

create sql query as string then exexute by exe statement in sql you can do rnd on that as well
 
Share this answer
 
Comments
Hidhoud1991 12-Sep-14 8:17am    
Ive added my query could u tell me how to do the exec?
Hi,

I have never tried the same but it can be done. From my point of view check below comments

1. Using "If Else" as you will pass parameter from front end.

2. You can also check the same by making use of dynamic SQLs.




Check this updated one....



Quote:Ive added my query could u tell me how to do the above comments


SQL
--PR_DYNAMIC_OPERATORS '>'
ALTER PROC PR_DYNAMIC_OPERATORS
(
@PA_OPERATOR VARCHAR(100)
)
AS
BEGIN

--First Option
/*
IF @PA_OPERATOR = '='
BEGIN

SELECT 1 WHERE 1 = 1

END

IF @PA_OPERATOR = '>'
BEGIN

SELECT 1 WHERE 2 > 1

END



--.
--.
--.
--.
--.
--and So On

*/


--Second Option

DECLARE @SQL VARCHAR(200)

SET @SQL = 'SELECT 1 WHERE 2 ' + @PA_OPERATOR + ' 1'
PRINT(@SQL)
EXEC (@SQL)


END





Hope this will help you.

Cheers
 
Share this answer
 
v3
Comments
Hidhoud1991 12-Sep-14 8:17am    
Ive added my query could u tell me how to do the above comments
Magic Wonder 12-Sep-14 9:05am    
Check my test proc. Hope this will help you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900