源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

sql存储过程详解

  • 时间:2020-03-07 19:32 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:sql存储过程详解
1,不带参数的存储过程 2,带输入参数的存储过程 3,带输入和输出参数的存储过程 4,带返回值的存储过程 不带参数的存储过程 例如,以下存储过程返回Employees表中所有职员的记录。 存储过程代码:
USE TSQLFundamentals2008;
GO

IF OBJECT_ID('usp_ProcDemoNoParam','P') IS NOT NULL DROP PROC usp_ProcDemoNoParam;
GO
-- 1,不带参数
CREATE PROC usp_ProcDemoNoParam
AS
BEGIN
  SELECT * FROM HR.Employees;
END
GO

调用代码:
USE TSQLFundamentals2008;
GO

-- 1,不带参数存储过程的调用
EXEC usp_ProcDemoNoParam;

结果: [img]http://files.jb51.net/file_images/article/201408/20148690741262.png?201476981[/img] 可以看到,共返回了9条记录。 带输入参数的存储过程 例如,该存储过程接受输入参数@empid,然后返回这个职员的信息。 创建存储过程代码:
IF OBJECT_ID('usp_ProcDemoWithInputParam','P') IS NOT NULL DROP PROC usp_ProcDemoWithInputParam;
GO
-- 2,带输入参数
CREATE PROC usp_ProcDemoWithInputParam
  @empid AS INT
AS
BEGIN
  SELECT * FROM HR.Employees
  WHERE empid= @empid;
END
GO

调用:
-- 2,带输入参数存储过程调用
EXEC usp_ProcDemoWithInputParam @empid=5;
结果: [img]http://files.jb51.net/file_images/article/201408/20148690839128.png?2014769850[/img] 带输入和输出参数的存储过程 例如,以下存储过程接受@empid即职员ID作为输入参数,然后返回该职员的信息,同时返回代码受影响行数作为输出参数。 创建存储过程代码:
IF OBJECT_ID('usp_ProcDemoWithInputOutputParam','P') IS NOT NULL DROP PROC usp_ProcDemoWithInputOutputParam;
GO
-- 3,带输入和输出参数
CREATE PROC usp_ProcDemoWithInputOutputParam
  @empid AS INT,
  @NumRowsAffected AS INT OUTPUT
AS
BEGIN
  SELECT * FROM HR.Employees
  WHERE empid= @empid;
  
  SET @NumRowsAffected= @@ROWCOUNT; -- 赋值,也可以使用select赋值
END
GO

调用:
-- 3,带输入和输出参数存储过程的调用
DECLARE @nums AS INT;
EXEC usp_ProcDemoWithInputOutputParam @empid=5,@NumRowsAffected= @nums OUTPUT;
SELECT @nums AS nums;
结果: [img]http://files.jb51.net/file_images/article/201408/20148690926302.png?2014769936[/img] 带返回值的存储过程 例如,以下存储过程接受@empid即职员ID作为输入参数,然后判断职员表中是否存在该职员的记录,如果存在则返回1,否则返回0. 创建存储过程代码:
IF OBJECT_ID('usp_ProcDemoWithReturnValue','P') IS NOT NULL DROP PROC usp_ProcDemoWithReturnValue;
GO
-- 4,带返回值
CREATE PROC usp_ProcDemoWithReturnValue
  @empid AS INT
AS
BEGIN
  IF EXISTS (SELECT * FROM HR.Employees WHERE empid=@empid)
    RETURN 1
  ELSE
    RETURN 0; -- 也可以声明一个变量,然后返回这个变量
END
GO

调用:
-- 4,带返回值存储过程的调用
DECLARE @status AS INT=0; --给默认值为0
EXEC @status= dbo.usp_ProcDemoWithReturnValue @empid = 5 -- int
SELECT @status AS thestatus;
结果: [img]http://files.jb51.net/file_images/article/201408/20148691004147.png?20147691016[/img]
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部