T-SQL(二)函数和存储过程

数据源
pubs 示例数据库
目标

1、编写自定义函数;
2、编写自定义存储过程;
3、编写客户端程序,实现调用存储过程,显示返回select结果集、返回值和输出参数。

代码

-- T-SQL
-- 定义函数
-- 函数通过作家的姓名检索出作家的ID结果集
create function get_author_id
  (
  @author_lname varchar(20),
    @author_fname varchar(20)
  )
  returns table
  as
    return(select authors.au_id from authors
    where @author_fname = authors.au_fname and @author_lname = authors.au_lname)

-- 定义存储过程
create proc get_author_titles_info
  @author_lname varchar(20),
    @author_fname varchar(20),
      @mark varchar(5) output
  as
  begin
    select titles.title_id, titles.title from titleauthor, titles
    where titleauthor.title_id = titles.title_id and titleauthor.au_id in (
      select *
      from get_author_id(@author_lname, @author_fname)
    )
    set @mark = 'yeah!'
    return 1
  end

-- 存储过程的返回值和输出值
create table call_proc_output(
  re varchar(20),
  m varchar(20)
)
# Python
import pymssql

# 连接本地示例数据库
conn = pymssql.connect(server='localhost', database='pubs')

# 创建游标
cur = conn.cursor()

# 执行 SQL 语句
sql = '''
declare @re int
declare @mark varchar(5)
drop table call_proc_output
create table call_proc_output(
  re varchar(20),
  m varchar(20)
)
exec @re = dbo.get_author_titles_info 'Green', 'Marjorie', @mark output
insert into call_proc_output values (@re, @mark)
'''
cur.execute(sql)

# 获取执行结果
result = cur.fetchall()

# 打印结果
print(result)
#

# 查看返回值和输出值
sql = '''
select * from call_proc_output
'''
cur.execute(sql)
result = cur.fetchall()
print(result)

# 关闭连接
conn.close()

猜你喜欢

转载自blog.csdn.net/lolimostlovely/article/details/82862050