How to dynamically generate the WHERE clause of SELECT statement during storage procedures when query conditions

xiaoxiao2021-03-06  15

WANGXL430 (Kara)

The possibility of query conditions may be, for example: may be select * from table1 where a> 4 and b <100 may also be select * from table1 where a = 10 and b <50 and c like 'aaa' '%' May be select * from table1 where c like 'bbb' '%' a variety of situations, the only thing that can be determined is that the maximum number of conditions is fixed. My idea is to give the parameters of each condition (if there is such a condition), how to execute the stored procedure, how to determine during storage procedures?

Reply to: Softlee81307 (Kong Kidney) () Reputation: 100

Give an example to you, you can change the table name to your table.

Create Procedure KP @ K varchar (300) as declare @s varchar (1000) set @ s = 'select * from the name where' @ K EXEC (@S) ------------- ----------------------------- EXEC KP 'A> 4 and B <100' --------- EXEC KP 'WHERE A = 10 and B <50 and c like' AAA ' '% ''

Reply to: daijingjie2002 (hard work) () Reputation: 97

Creter, @ b integer, @ c varchar (50) asdeclare @ss varchar (8000), @ ii integrator @ ii = 0select @ ss = 'select * from table Where' if @a not is null begin Select @ ss = @ ss 'a =' '' @ a '' SELECT @ II = 1ENDIF @B NOT IS NULLBEGIN IF @ II = 0 Begin Select @ ss = @ ss 'b =' '' @ b ' 'SELECT @ II = 1 END ELSE BEGIN SELECT @ SS = @ SS ' and B = ' ' ' @ B ' 'Endendif @C Not is Nullbegin IF @ ii = 0 Begin Select @ ss = @ SS ' C Like ' '' @ C '%' '' SELECT @ II = 1 END ELSE BEGIN SELECT @ SS = @ SS 'AND C LIKE' '' @ C '%' 'Endendexec (@ss)

转载请注明原文地址:https://www.9cbs.com/read-45795.html

New Post(0)