存储过程中的参数比较

时间:2014-02-13 12:30:47

标签: sql sql-server-2008

我创建了以下存储过程,接受2个参数。有没有办法比较表中特定列的参数?基本上希望用户输入proj_num和newDate,如果他们在表中显示一些信息。

CREATE PROCEDURE empInfo2 
(
     @proj_num AS char(3)
    ,@newDate AS smalldatetime 
)
AS
BEGIN
/* Insert IF Statement here Intent is to display an ERROR message
if the proj_num and/or date are not within the tables*/

IF (@proj_num <> /*Compare to PROJ_NUM column to see if number is in range*/
    OR /* I assume @newDate must be compared to ASSIGN_DATE?? */ )
    PRINT 'Invalid input. Enter correct Project Number and Date.'


SELECT EMPLOYEE.EMP_NUM
      ,EMPLOYEE.EMP_FNAME
      ,EMPLOYEE.EMP_LNAME
      ,PROJECT.PROJ_NUM
      ,ASSIGNMENT.ASSIGN_DATE

FROM   ASSIGNMENT INNER JOIN EMPLOYEE ON
       ASSIGNMENT.EMP_NUM = EMPLOYEE.EMP_NUM INNER JOIN
       PROJECT ON ASSIGNMENT.PROJ_NUM = PROJECT.PROJ_NUM

WHERE  PROJECT.PROJ_NUM = @proj_num AND ASSIGN_DATE = @newDate  
END

2 个答案:

答案 0 :(得分:1)

IF (@proj_num NOT IN (SELECT ...)) OR (@newDate NOT IN (SELECT ...))
    PRINT 'Invalid input. Enter correct Project Number and Date.'

答案 1 :(得分:0)

它可能包含一些语法错误,但想法是

CREATE PROCEDURE empInfo2 
(
     @proj_num AS char(3)
    ,@newDate AS smalldatetime 
)
AS
BEGIN
/* Insert IF Statement here Intent is to display an ERROR message
if the proj_num and/or date are not within the tables*/

   IF ( NOT EXISTS (
         SELECT 1 FROM PROJECT WHERE PROJ_NUM = @proj_num
                               AND ASSIGN_DATE = @newDate ) 
    BEGIN
       PRINT 'Invalid input. Enter correct Project Number and Date.'
    END
   ELSE

  SELECT EMPLOYEE.EMP_NUM
  ,EMPLOYEE.EMP_FNAME
  ,EMPLOYEE.EMP_LNAME
  ,PROJECT.PROJ_NUM
  ,ASSIGNMENT.ASSIGN_DATE

  FROM   ASSIGNMENT INNER JOIN EMPLOYEE ON
     ASSIGNMENT.EMP_NUM = EMPLOYEE.EMP_NUM INNER JOIN
      PROJECT ON ASSIGNMENT.PROJ_NUM = PROJECT.PROJ_NUM

  WHERE  PROJECT.PROJ_NUM = @proj_num AND ASSIGN_DATE = @newDate  

  END