MS SQL Common SQL Statements (4): Create, Modify, Delete the SQL of Stored Procedures

4. Stored procedure operation:

--1, create a stored procedure
--grammar structure:
--Create Proc procedure name
--@Parameter parameter type
--[,@Parameter parameter type output]
--As
--Begin
--....
--end

--without parameters
create proc newProc
as
begin
declare @str varchar(50);
set  @str='123456';
print @str;
end

--with parameters
create procedure newProc2
@testStr varchar(50), -- no comma if there is only one parameter
@testStr2 varchar(50)
As
begin
	print 'The value of the first parameter is: '+@testStr;
	print 'The value of the second parameter is: '+@testStr2;
end

--with output value
create procedure newProc3
@test int,
@test2 int,
@testSum int output
as
begin
	set @testSum = @test+@test2;
end

--2, execute the stored procedure
--Syntax structure: exec|execute proc|procedure procedureName [parameters];
exec newProc;-- takes no arguments and returns no value
exec newProc2 '123456','ABCDEFG';--with parameters, no return value

--With parameters, there is a return value
declare @testSum int;
set @testSum=100;
print @testSum;
exec newProc3 10,20,@testSum output;
print @testSum;

--3. View the stored procedure:
select * from sysobjects where xtype='P'
--or
SELECT name, definition
FROM sys.sql_modules AS m
INNER JOIN sys.all_objects AS o ON m.object_id = o.object_id
WHERE o.[type] = 'P'

--xtype can be replaced with the following parameters:
--C=CHECK constraint
--D = default or DEFAULT constraint
--F = FOREIGN KEY constraint
--L = log
--FN = scalar function
--IF = inline table function
--P = stored procedure
--PK = PRIMARY KEY constraint (type is K)
--RF=Replicate Filter Stored Procedure
--S = system table
--TF = table function
--TR = trigger
--U = user table
--UQ=UNIQUE constraint (type is K)
--V = view
--X = extended stored procedure

--4, modify the stored procedure
--The modification is consistent with the creation syntax structure, that is, the created keyword can be modified to the alter keyword. As for the business logic, it can be modified according to the actual situation.
alter proc newProc
as
begin
declare @str varchar(50);
set  @str='123abc';
print @str;
end

--5, rename the stored procedure name
--Syntax structure: exec sp_rename 'the original name of the stored procedure', 'the new name of the stored procedure';
exec sp_rename 'newProc','newProc1';
-- may generate a warning: changing any part of the object name may break scripts and stored procedures.

--6, delete the stored procedure
--Syntax structure: exec procedure stored procedure name [, stored procedure, stored procedure];
drop procedure newProc;
drop procedure newProc2,newProc3;

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326516506&siteId=291194637