创建一个存储过程,在每个表上检索,更新和删除记录

时间:2015-07-16 11:47:50

标签: sql-server stored-procedures sql-server-2014 sql-server-2014-express

CREATE TABLE Person
(
ID INT Primary Key Identity (1,1),
LastName nVarchar (20) not NULL, 
FirstName nVarchar (20) not NULL, 
MiddleName nVarchar (20), 
BirthDate DateTime not NULL, 
Age INT not NULL, 
Check (Age>18) 
);


CREATE TABLE Department
(
ID INT Primary Key Identity (1,1), 
DepartmentName nVarchar (50) Unique, 
DepartmentCode nVarchar (20) Unique, 
IsActive Bit Default (1)
); 


CREATE TABLE Employee
(
ID INT Primary Key Identity (1,1), 
PersonId INT Foreign Key REFERENCES Person, 
DepartmentId INT Foreign Key REFERENCES Department, 
Salary Decimal (18,2), 
Check (Salary>10000), 
IsActive Bit Default (1) 
); 

我尝试使用此功能,但我不太确定这是否正确。

    CREATE PROCEDURE sp_retrieve 
    AS 
    BEGIN 
    SELECT * FROM Person 
    END 
    GO 

如何正确创建存储过程以进行检索,更新和删除?

1 个答案:

答案 0 :(得分:0)

CREATE PROCEDURE usp_Test123
AS
SELECT 'This is a test'

CREATE PROCEDURE usp_Update @Col1Val NVARCHAR(MAX)
AS
UPDATE ReplaceTableNameHere
SET Column1 = @Col1Val

CREATE PROCEDURE usp_Insert @Col1Val NVARCHAR(MAX)
AS
INSERT INTO ReplaceTableNameHere (Col1)
VALUES (Column1 = @Col1Val)

CREATE PROCEDURE usp_delete @PKID NVARCHAR(MAX)
AS
DELETE ReplaceTableNameHere
WHERE ColumnPKID = @PKID

编辑:您可以在执行存储过程时传入值以允许选择,更新和删除。

更新示例:

EXEC usp_Update @Col1Val = 50;

这会将您在存储过程中定义的表更新为值50。