Home > Database > Mysql Tutorial > SQL创建的几种存储过程

SQL创建的几种存储过程

WBOY
Release: 2016-06-07 18:00:24
Original
842 people have browsed it

表名和比较字段可以做参数的存储过程

创建存储过程
表名和比较字段可以做参数的存储过程
Create PROCEDURE sp_getTeacherInfo
@TblName nvarchar(30), -- 表名
@CmpStr nvarchar(30), -- 参与比较的值
@TblAtr nvarchar(30) -- 参与比较的字段
AS
DECLARE @sql varchar(4000)
SET @sql = 'select * from ' + @TblName + ' where ' + @TblAtr + '=' + @CmpStr
EXEC (@sql)


表 tbl_TeacherInfo


Exec sp_getTeacherInfo 'tbl_TeacherInfo','TeaNo', '07417502'
// 注意:像这样的调用是错误的
还原成查询语句
select * from tbl_TeacherInfo where TeaNo = 07417502
之所以没报错,是因为参数'07417502'被误认为了 整型,进行了整数的比较

Exec sp_getTeacherInfo 'tbl_TeacherInfo','Name','楚留香'
// 报错
还原成查询语句
select * from tbl_TeacherInfo where TeaNo = 楚留香
// 显然是错误的

正确的调用方法
Exec sp_getTeacherInfo 'tbl_TeacherInfo','Name',"'楚留香' "
还原成查询语句
select * from tbl_TeacherInfo where TeaNo = '楚留香'

常规存储过程的创建
Create PROCEDURE sp_AddRowToLogin
@TeaNo nvarchar(100), -- 比较字段
@TeaName nvarchar(100) -- 比较字段
AS
insert into tbl_UserLogin values(@TeaNo,@TeaName,@TeaNo,0)


除了指定列其他列都返回的存储过程
CREATE PROCEDURE sp_Alter
@TblName nvarchar(30) -- 表名
AS
declare @sql varchar(1000)
select @sql='select '
select @sql=@sql+name+',' from syscolumns where id=object_id(@TblName) and name not in ('ID','TeaNo')
select @sql=left(@sql,len(@sql)-1)
select @sql=@sql+' from ' + @TblName
exec (@sql)

// 除了ID和TeaNo两列不返回,其他都返回

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template