SQL Server存储过程和计数

时间:2016-06-01 13:08:54

标签: sql sql-server stored-procedures

嗨,我对SQL比较陌生。我正在尝试创建一个存储过程来计算带有一些标准的recrods。如果计数<> 1然后我希望它打印一个值,以便我可以将它传递回VB6中的应用程序。

我想要做的是找出一个员工是否已经访问过某个应用程序,如果他们这样做的话......

select sum(clientid) as NumClients 
from TblEmployee 
where clientid = '1709' 
      and ApplicationID='Excel'

然后我想检查计数,但我有点迷失在synthax上,有点像

if NumClients <> 1
    begin
        Print '1'
        go
    end

4 个答案:

答案 0 :(得分:1)

做这样的事情:

CREATE PROCEDURE [dbo].[usp_EmpCheck]
    (
    @ClientID INT,
    @App VARCHAR(50),
    @CheckResult BIT OUTPUT
    )
AS
BEGIN

    IF (
        SELECT
            SUM(clientid) 
        FROM
            TblEmployee 
        WHERE
            clientid = @ClientID 
            AND ApplicationID = @CheckResult
        ) <> 1
        BEGIN
            SET @CheckResult = 1
        END
    ELSE
        BEGIN
            SET @CheckResult = 0
        END
END

然后让VB执行过程OUTPUT参数的值。

答案 1 :(得分:0)

试试这个。

ALTER PROCEDURE TestSP
(
    @clientid  INT,
    @ApplicationID  INT,
    @result BIT OUTPUT
)
AS
BEGIN

   DECLARE @count INT;

   SELECT @count= CASE   WHEN COUNT(clientid )>=1 THEN 1
                         ELSE 0
                         END
   FROM TblEmployee 
   WHERE clientid = @clientid
        AND ApplicationID = @ApplicationID

   SET @result = @count

END
GO

答案 2 :(得分:0)

IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   type = 'P'
                    AND name = 'sp_Count' )
    DROP PROCEDURE [dbo].[sp_Count];
GO 

CREATE PROCEDURE [dbo].[sp_Count]
AS
    DECLARE @Sum INT;
    SELECT  @Sum = SUM(CompanyID) FROM   dbo.Company;

    PRINT @Sum;

    IF ( @Sum > 1 )
        BEGIN

            PRINT 'More than one';
        END;
    ELSE
        BEGIN
            PRINT 'zero';
        END;
        ---- sp_Count

答案 3 :(得分:0)

SQL代码:

 CREATE PROCEDURE [dbo].[check_number]
     (
     @ClientID INT,
     @App VARCHAR(50)
     )
 AS

 select case number
            WHEN 1 then 'not what you want'
            ELSE 'what you want'
        END as result
 FROM 
 (SELECT count(1) as number
  FROM   TblEmployee 
  WHERE  clientid = @ClientID 
    AND ApplicationID = @CheckResult ) as results

您的vb6代码可能如下所示:

 Set cmd = New ADODB.Command
  cmd.ActiveConnection = con
  cmd.CommandType = adCmdStoredProc
  cmd.CommandText = "check_number

  cmd.Parameters.Append cmd.CreateParameter_
    ("ClientID", adint, adParamInput, yourClientIdParamValue)
  cmd.Parameters.Append cmd.CreateParameter_
    ("App", adVarChar, adParamInput, 50, yourAppValue)

  Set rs = cmd.Execute

  If Not rs.EOF Then
   if rs.Fields(0) = 'what you want' then
    'do what you want !
   End if
  End If

  Set cmd.ActiveConnection = Nothing

 End Sub

我不确定我的语法对于vb6

是100%正确的