如何使用参数默认值从sql数据库中选择所有记录? [英] How do I select all records from sql database using parameters default value?

查看:142
本文介绍了如何使用参数默认值从sql数据库中选择所有记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所拥有的是一个复选框列表,显示所有学生选择批次..

现在我有3个下拉列表,根据科目,百分比等过滤学生...

是否有任何关键字(如NULL)或技巧被设置为select参数的默认值,以便最初从数据库中选择所有记录,然后根据用户输入进行过滤...

What i have is an checkboxlist showing all students for selection of an batch..
Now i have 3 dropdownlist for filtering students according to subjects,percentage,etc...
Is there any keyword (like NULL) or trick to be set as default of select parameter to select all records from database initially then filter according to user input...

推荐答案

如果我理解正确,你可以使用存储过程,如果你传递的参数是Null,那么它仍然会运行存储过程。见下:



If I understand correctly you can use a stored procedure and if the parameter you pass it is Null, then it will still run the stored procedure. See below:

ALTER PROCEDURE [dbo].[spYourStoredProcedure]
	-- Add the parameters for the stored procedure here
	@Parameter VARCHAR(15) = NULL	
AS

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	--SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
END





如果没有任何内容传递给存储过程,则上面的代码行将为NULL。如果Parameter值为NULL,则在决定运行哪个查询之前检查它。



The above line of code will be a value of NULL if nothing is passed to the stored procedure. If the Parameter value is NULL, then you check for that before you decide which query to run.


您可以将NULL值传递给参数并检入该值的存储过程。如果为NULL则不在查询中传递该参数。



如果您有更多参数,那么您可以使用动态SQL。



例如。



ALTER PROCEDURE [dbo]。[TestSP]



@ Parameter1 VARCHAR(15)= NULL,

@ Parameter2 VARCHAR(15)= NULL,

@ Parameter3 VARCHAR(15)= NULL

AS



BEGIN



声明@wherecond varchar(200)

SET @wherecond =''

if(@ Parameter1!= NULL)

SET @wherecond ='AND parameter1 = @ parameter1'

endif

if(b @ Parameter2!= NULL)

SET @wherecond ='AND parameter2 = @ parameter2'

endif



- 最终查询

select * from< your table =>其中1 = 1 + @ wherecond



END
You can pass NULL value to parameter and check in store procedure for that value. If it is NULL then not to pass that parameter in query.

If you have more number of parameters, so you can use dynamic SQL.

Eg.

ALTER PROCEDURE [dbo].[TestSP]

@Parameter1 VARCHAR(15) = NULL,
@Parameter2 VARCHAR(15) = NULL,
@Parameter3 VARCHAR(15) = NULL
AS

BEGIN

Declare @wherecond varchar(200)
SET @wherecond = ''
if (@Parameter1 != NULL)
SET @wherecond = ' AND parameter1 = @parameter1'
endif
if (@Parameter2 != NULL)
SET @wherecond = ' AND parameter2 = @parameter2'
endif

-- Final Query
select * from <your table=""> where 1=1+@wherecond

END


这篇关于如何使用参数默认值从sql数据库中选择所有记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆