天天看点

【机房重构】组合查询—存储过程

        存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,存储在数据库中,经过第一次编译后再次调用不需要再次编译,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象,任何一个设计良好的数据库应用程序都应该用到存储过程。

        在组合查询中用到了存储过程,遇到了一堆错误。经过小伙伴儿们的帮忙,和艰苦的调试,终于调出了错误。

调试完错误后的存储过程是这样的:(在主程序调用前要把参数的初始值去掉,由程序中获得,测试为了方便才如此做)

USE [RoomCharge]
GO
/****** Object:  StoredProcedure [dbo].[PROC_CombinedQuery]    Script Date: 11/13/2015 19:40:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	李爽
-- Create date: 2015-11-10
-- Description:	实现组合查询,学生上机记录查询,教师工作记录查询和学生基本信息维护
-- =============================================
ALTER PROCEDURE [dbo].[PROC_CombinedQuery] 
	-- Add the parameters for the stored procedure here
	@DbName nvarchar(50)='stuOnlineRecord_Info',
	@cboFileName1 nvarchar(20)='StudentName',
	@cboOperator1 nvarchar(10)='=',
	@txtContent1 nvarchar(20)='1',
	@cboRelation1 nvarchar(10) = '',
	@cboFileName2 nvarchar(20)='CardNo',
	@cboOperator2 nvarchar(10)='=',
	@txtContent2 nvarchar(20)='1',
	@cboRelation2 nvarchar(10)='and',
	@cboFileName3 nvarchar(20)='StudentNo',
	@cboOperator3 nvarchar(10)='=',
	@txtContent3 nvarchar(20)='1'	
AS

declare @TempSql varchar(500)--临时存放sql语句 
   --CHAR(32)是空格,CHAR(39)单引号 

 begin 

       --一个条件查询
	 set @TempSql ='select * from ' [email protected]+' where'+char(32)+
	@[email protected] +char(39)[email protected] +char(39)
	  
	if(@cboRelation1 != null) 
	begin
   
 --两个条件查询

 set @TempSql [email protected] +char(32) [email protected] +char(32)[email protected] [email protected] +char(39)[email protected] +char(39)if(@cboRelation2 != null) 
begin
          
--三个条件查询

 set @TempSql [email protected] +char(32)[email protected]+char(32)[email protected] [email protected] +char(39)[email protected] +char(39)endendexecute (@Tempsql) --执行查询语句
end
           

这次主要遇到这么几个错误:

1、存储过程中SQL语句的小标点,万万大意不得。

    正确写法:

         @TempSql='select * from ' [email protected]+' where'+char(32)[email protected][email protected]+char(39)[email protected] +char(39)

注意:from右边和where左边均有一个空格,必不可少。

    错误写法:

         @TempSql='select * from'+char(39)[email protected]+char(39)+'where'+char(32)[email protected][email protected] +char(39)[email protected] +char(39)

注意:在单引号的句子中的单引号外不可以再用char(32)等ascii码。而应该向正确写法一样用单引号里边的空格。当然单引号内部不可以用ascii过程中SQL语句的小标点码。

2、存储过程中空值Null

    Isnot Null(is null)  VS  !=null(=null)

    is null:用来确定表达式是否为Null

    =null:用来确认参数是否为Null

--给参数赋值:

@cboRelation1=''--(1)表示参数是null

@cboRelation1=null  --(2)表示参数是null

@cboRelation1 is not null --(3)会有语法错误

 

--判断参数是否符合条件

if(@cboRelation1 is not null) --在(1)的参数情况下会有语法错误,在(2)的参数情况下可以执行。(这里表示判断表达式是否为空)

if(@cboRelation1 != null) --在(1)(2)的参数情况下都可以执行。(在这里表示判断参数值是否为空)
           

继续阅读