我想检查是否存在存储过程列表。我希望所有这些都在1个脚本中一个接一个地完成。到目前为止,我有这种格式:8 D1 x0 a4 A# x5 h6 n
USE [myDatabase] $ r5 r7 o& [! p6 v C( pGO ) p& n' g% W9 R& e! w0 e& NIF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'sp_1') B, \+ g5 f) u9 g& TBEGIN7 ?2 X% a+ t4 {: k- m* S7 J# F
CREATE PROCEDURE sp_1 4 H: s4 n' `" F+ v7 bAS 6 n6 ^9 j+ Z' Z.................0 ? K* y- {3 I! w5 b
END! _0 _, ]4 M2 k$ U" ]
GO 5 q3 J9 u4 d+ \! T* i2 F+ wIF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'sp_2')( }. i t8 r5 T4 ?; r
BEGIN 6 ^; b- X4 l" J4 q0 M a7 HCREATE PROCEDURE sp_2 + X, Q! l8 P6 m* a9 f# l$ ^AS 4 j" ]5 f) |/ m3 K' B& ].................8 ]; |1 {# D9 G
END 2 ]8 b* o( E* t* G! zGO ! x; G* q( I+ _" X8 Y. J7 K' r8 E等等。但是,出现以下错误:" V0 }8 C2 L; z - h' `( O" i- |" R关键字“过程”附近的语法不正确。# { s2 S5 H6 `0 U $ P1 h0 I }1 v
为什么我的工作不正常? . N7 G# ^. j* `4 }% i % e- }( ] m; Z2 Y* q! k 解决方案:0 q6 Z( b4 Q7 y
2 O/ S5 [4 U4 |5 ]7 c% m # U: k0 p# c+ @; ~/ k & E. k8 x1 q" M" q* K, I8 q CREATE PROCEDURE必须是批处理中的第一个语句。我通常会这样: . u7 g2 S7 ]4 o3 U7 [IF EXISTS ( 8 I0 k, r! W7 m SELECT type_desc, type 3 A( {0 m. y) Y9 j FROM sys.procedures WITH(NOLOCK) + C5 h8 E* {5 g8 Q1 p% m WHERE NAME = 'myProc' 0 \+ R& |5 V ]8 Q- G: z- l AND type = 'P' / e+ l* Z$ h J. ]" J( b ) 1 R& J& b f1 P+ H DROP PROCEDURE dbo.myProc + j' P+ X! @7 {: F- ?# jGO4 U" S' w! B; g u
CREATE PROC dbo.myProc+ e- q( E' g9 M/ {* d; O" y; p
AS6 y+ E& x1 k( i
.... Y1 I1 G: S# _# p GO/ K0 H: Z r+ [1 H0 c" H
GRANT EXECUTE ON dbo.myProc TO MyUser ( H3 Z9 `4 H1 s+ G(不要忘记授予声明,因为如果您重新创建proc,它们将会丢失) 5 T% G" T% t- F$ ]8 h }; H部署存储过程时要考虑的另一件事是,删除可以成功而创建失败。出现问题时,我总是使用回滚来编写SQL脚本。只要确保您不会在结尾时意外删除提交/回滚代码,否则您的DBA可能会在气管中将您吊起踢 P- C4 W% z m3 v: Q$ \9 o
BEGIN TRAN + N$ d% J7 y9 Q$ l* ~9 `IF EXISTS (7 a E" Y" ?8 d; a
SELECT type_desc, type6 d9 ^5 x3 l1 b, v3 w4 i7 \
FROM sys.procedures WITH(NOLOCK) 3 [+ @ i. ^0 p5 @) e2 [% z WHERE NAME = 'myProc' 4 F: [" `& N3 D9 Z AND type = 'P' + T! U' _* H8 L( @ [5 } )3 _2 O, v3 e% A: O# p. b0 c
DROP PROCEDURE myProc GO ) c$ Y# _4 t, zCREATE PROCEDURE myProc 0 L5 c+ M) ^+ L3 x3 A" WAS 8 d. Y" Y6 C9 x/ K3 R- H! ? --proc logic here1 f Z- f6 K5 z; Z w* Q4 Q
GO 0 ~ {* ? j" `* x-- BEGIN DO NOT REMOVE THIS CODE (it commits or rolls back the stored procedure drop) 6 C& L. D I) V- X$ O( ]9 f IF EXISTS( 3 [- S1 s; j, X8 O% L( H6 L( Q SELECT 1 * g! h7 e& G$ R1 Y/ E: c' M$ z FROM sys.procedures WITH(NOLOCK) " S7 y _- l5 j: R- {/ L. x$ A ] WHERE NAME = 'myProc'. V) ?: Y' o) }, L$ `9 C
AND type = 'P' ! _. M) ]& l( B3 o ) 9 I* R" u" R, `; o COMMIT TRAN * ^+ _: j% B, q- {7 F5 t. A ELSE7 j. F( `% t! |3 o
ROLLBACK TRAN' S! H9 Q I, v6 L
-- END DO NOT REMOVE THIS CODE