저장 프로 시저가 이미 있는지 확인하는 방법
저장 프로 시저가 존재하거나 존재하지 않는 경우 작동하는 배포 스크립트를 작성해야합니다. 즉, 존재하는 경우 변경해야하며, 그렇지 않으면 작성해야합니다.
SQL에서 어떻게 할 수 있습니까?
SQL Server 2005를 사용하고 있습니다
프로 시저를 삭제하고 작성하면 보안 설정이 해제됩니다. 이로 인해 DBA가 성가 시거나 애플리케이션이 완전히 중단 될 수 있습니다.
내가하는 일은 아직 간단한 저장 프로 시저를 만들지 않는 것입니다. 그런 다음 저장 프로 시저를 원하는대로 변경할 수 있습니다.
IF object_id('YourSp') IS NULL
EXEC ('create procedure dbo.YourSp as select 1')
GO
ALTER PROCEDURE dbo.YourSp
AS
...
이런 식으로 보안 설정, 주석 및 기타 메타 데이터는 배포 후에도 유지됩니다.
가장 깨끗한 방법은 존재 여부를 테스트하고 존재하는 경우 삭제 한 다음 다시 작성하는 것입니다. IF 문 안에 "create proc"문을 포함시킬 수 없습니다. 이것은 잘해야합니다 :
IF OBJECT_ID('MySproc', 'P') IS NOT NULL
DROP PROC MySproc
GO
CREATE PROC MySproc
AS
BEGIN
...
END
저장 프로 시저 만 처리하는 경우 가장 쉬운 방법은 proc을 삭제 한 다음 다시 만드는 것입니다. SQL Server의 스크립트 생성 마법사를 사용하여이 작업을 수행하는 모든 코드를 생성 할 수 있습니다.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[YourSproc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[YourSproc]
CREATE PROCEDURE YourSproc...
에서 SQL Server 2016 CTP3
당신은 새 사용할 수 있습니다 다이 문 대신 큰 IF
래퍼를
통사론:
삭제 {PROC | 절차} [존재하는 경우] {[schema_name. ] 절차} [, ... n]
질문:
DROP PROCEDURE IF EXISTS usp_name
더 많은 정보는 여기에
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[xxx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
CREATE PROCEDURE dbo.xxx
xxx
proc 이름은 어디에 있습니까
이미 말한 것 외에도 다른 접근 방식을 추가하고 차등 스크립트 배포 전략의 사용을 옹호하고 싶습니다. 항상 현재 상태를 확인하고 해당 상태를 기반으로 작동하는 상태 저장 스크립트를 만드는 대신, 잘 알려진 버전에서 업그레이드하는 일련의 상태 비 저장 스크립트를 통해 배포하십시오 . 필자는이 전략을 사용했으며 이제 배포 스크립트가 모두 'IF'가 아니므로 시간이 많이 걸립니다.
IF OBJECT_ID('SPNAME') IS NULL
-- Does Not Exists
ELSE
-- Exists
다음과 같이 쿼리를 작성할 수 있습니다.
IF OBJECT_ID('ProcedureName','P') IS NOT NULL
DROP PROC ProcedureName
GO
CREATE PROCEDURE [dbo].[ProcedureName]
...your query here....
To be more specific on the above syntax:
OBJECT_ID is a unique id number for an object within the database, this is used internally by SQL Server. Since we are passing ProcedureName followed by you object type P which tells the SQL Server that you should find the object called ProcedureName which is of type procedure i.e., P
This query will find the procedure and if it is available it will drop it and create new one.
For detailed information about OBJECT_ID and Object types please visit : SYS.Objects
I have a stored proc that allows the customer to extend validation, if it exists I do not want to change it, if it doesn't I want to create it, the best way I have found:
IF OBJECT_ID('ValidateRequestPost') IS NULL
BEGIN
EXEC ('CREATE PROCEDURE ValidateRequestPost
@RequestNo VARCHAR(30),
@ErrorStates VARCHAR(255) OUTPUT
AS
BEGIN
SELECT @ErrorStates = @ErrorStates
END')
END
The code below will check whether the stored procedure already exists or not.
If it exists it will alter, if it doesn't exist it will create a new stored procedure for you:
//syntax for Create and Alter Proc
DECLARE @Create NVARCHAR(200) = 'Create PROCEDURE sp_cp_test';
DECLARE @Alter NVARCHAR(200) ='Alter PROCEDURE sp_cp_test';
//Actual Procedure
DECLARE @Proc NVARCHAR(200)= ' AS BEGIN select ''sh'' END';
//Checking For Sp
IF EXISTS (SELECT *
FROM sysobjects
WHERE id = Object_id('[dbo].[sp_cp_test]')
AND Objectproperty(id, 'IsProcedure') = 1
AND xtype = 'p'
AND NAME = 'sp_cp_test')
BEGIN
SET @Proc=@Alter + @Proc
EXEC (@proc)
END
ELSE
BEGIN
SET @Proc=@Create + @Proc
EXEC (@proc)
END
go
A better option might be to use a tool like Red-Gate SQL Compare or SQL Examiner to automatically compare the differences and generate a migration script.
참고URL : https://stackoverflow.com/questions/937908/how-to-detect-if-a-stored-procedure-already-exists
'IT' 카테고리의 다른 글
폴더가 비어 있는지 빠르게 확인하는 방법 (.NET)? (0) | 2020.07.07 |
---|---|
요소가 다른 여러 HTML 요소가 동일한 ID를 가질 수 있습니까? (0) | 2020.07.07 |
여러 파일에 쓰도록 Log4net 구성 (0) | 2020.07.07 |
메이븐 오류 : 메인 클래스 org.codehaus.plexus.classworlds.launcher.Launcher를 찾거나로드 할 수 없습니다 (0) | 2020.07.07 |
문자열의 왼쪽 부분을 제거하는 방법? (0) | 2020.07.07 |