问题:写一个SQL存储过程,建立一个表USER 字段是姓名,年龄,职位,权限,然后向里面插入6条数据,然后查询出年龄大于18的所有信息。
答案:
--建立表以及插入数据
- use pubs
- go
- create table users(
- Name varchar(20),
- Age int,
- Position varchar(20),
- quanxian varchar(20)
- )
- Insert into users values('111',11,'11111','1111111');
- Insert into users values('112',12,'11112','1111112');
- Insert into users values('113',13,'11113','1111113');
- Insert into users values('114',14,'11114','1111114');
- Insert into users values('115',15,'11115','1111115');
- Insert into users values('116',19,'11116','1111116');
建立存储过程:(sql server 2005)
- set ANSI_NULLS ON
- set QUOTED_IDENTIFIER ON
- go
--这是数据库中的标准写法,当然你也可以不需要这么写。
- -- =============================================
- -- Author: <Author,,Name>
- -- Create date: <Create Date,,>
- -- Description: <Description,,>
- -- =============================================
- CREATE PROCEDURE [dbo].[selectUser]
- 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 * from users where age>18
- END
你也可以如下面这么写:
- CREATE PROCEDURE selectUser
- AS
- BEGIN
- SELECT * FROM users WHERE age>15
- END
-执行存储过程
- exec selectUser
--标准的写法是:
- USE [pubs]
- GO
- DECLARE @return_value int
- EXEC @return_value = [dbo].[selectUser]
- SELECT 'Return Value' = @return_value
- GO
删除存储过程:
--标准写法
- USE [pubs]
- GO
- /****** 对象: StoredProcedure [dbo].[selectUser]
- 脚本日期: 07/17/2011 16:10:44 ******/
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[selectUser]') AND type in (N'P', N'PC'))
- DROP PROCEDURE [dbo].[selectUser]
--不太标准的写法
- DROP PROCEDURE selectUser;
关于SQL存储过程就介绍到这里了,相信通过这个题,大家会对SQL存储过程有更深一步的理解。
【编辑推荐】