저장 프로 시저에 대한 명명 규칙은 무엇입니까? [닫은]
저장 프로 시저의 이름을 지정하기위한 다양한 규칙을 보았습니다.
어떤 사람들은 sproc 이름 앞에 usp_를 붙이고 다른 사람들은 앱 이름을 약어로 사용하고 다른 사람들은 소유자 이름을 붙입니다. 실제로 의미하지 않는 한 SQL Server에서 sp_를 사용하면 안됩니다.
일부는 동사 (Get, Add, Save, Remove)로 proc 이름을 시작합니다. 다른 사람들은 실체 이름을 강조합니다.
수백 개의 sproc이있는 데이터베이스에서는 이미 존재한다고 생각할 때 스크롤하고 적절한 sproc를 찾기가 매우 어려울 수 있습니다. 명명 규칙을 사용하면 sproc를보다 쉽게 찾을 수 있습니다.
명명 규칙을 사용합니까? 설명하고 다른 선택보다 선호하는 이유를 설명하십시오.
답글 요약 :
- 모든 사람이 명명의 일관성을 옹호하는 것 같습니다. 모든 사람이 특정 명명 규칙을 사용하는 것과 동일한 명명 규칙을 사용하는 것이 더 중요 할 수 있습니다.
- 접두사 : 많은 사람들이 usp_ 또는 이와 유사한 것을 사용하지만 (그러나 거의 sp_는 아니지만) 많은 사람들이 데이터베이스 나 앱 이름을 사용합니다. 한 영리한 DBA는 gen, rpt 및 tsk를 사용하여 일반 CRUD 프로 시저를보고 또는 작업에 사용 된 것과 구별합니다.
- 동사 + 명사는 명사 + 동사보다 약간 더 인기있는 것 같습니다. 어떤 사람들은 동사에 대해 SQL 키워드 (선택, 삽입, 업데이트, 삭제)를 사용하는 반면 다른 사람들은 가져 오기 및 추가와 같은 비 SQL 동사 (또는 약어)를 사용합니다. 일부는 단일 또는 복수의 명사를 구별하여 하나 이상의 레코드가 검색되는지 여부를 나타냅니다.
- 적절한 경우 끝에 추가 문구가 제안됩니다. GetCustomerById, GetCustomerBySaleDate.
- 어떤 사람들은 이름 세그먼트 사이에 밑줄을 사용하고 어떤 사람들은 밑줄을 피합니다. app_ Get_Customer vs. appGetCustomer-가독성 문제인 것 같습니다.
- 대량의 sproc 모음을 Oracle 패키지 또는 Management Studio (SQL Server) 솔루션 및 프로젝트 또는 SQL Server 스키마로 분리 할 수 있습니다.
- 피할 수없는 약어는 피해야합니다.
내가 한 대답을 선택하는 이유 : 좋은 답변이 너무 많습니다. 다들 감사 해요! 보시다시피, 하나만 선택하는 것은 매우 어렵습니다. 내가 선택한 것은 나와 공명했다. Verb + 명사를 사용하려고했지만 고객에게 적용되는 모든 sproc을 찾을 수없는 것과 동일한 경로를 사용했습니다.
기존 sproc을 찾거나 존재하는지 여부를 결정하는 것이 매우 중요합니다. 누군가 실수로 다른 이름으로 중복 sproc을 생성하면 심각한 문제가 발생할 수 있습니다.
일반적으로 수백 개의 sproc을 가진 매우 큰 앱에서 작업하기 때문에 가장 찾기 쉬운 이름 지정 방법을 선호합니다. 더 작은 응용 프로그램의 경우 메서드 이름에 대한 일반적인 코딩 규칙을 따르므로 동사 + 명사를 옹호 할 수 있습니다.
또한 유용하지 않은 usp_ 대신 앱 이름으로 접두사를 옹호합니다. 여러 사람들이 지적했듯이 때로는 데이터베이스에 여러 앱에 대한 sproc이 포함되어 있습니다. 따라서 앱 이름으로 접두어를 지정하면 sproc을 분리하고 DBA 및 기타 사용자가 sproc이 사용되는 앱을 결정할 수 있습니다.
마지막 프로젝트에서는 usp_AddProduct 또는 usp_GetProductList, usp_GetProductDetail과 같이 usp_ [Action] [Object] [Process]를 사용했습니다. 그러나 이제 데이터베이스는 700 개의 프로 시저에 더해 특정 오브젝트에서 모든 프로 시저를 찾기가 훨씬 어려워집니다. 예를 들어 이제 제품 추가에 대해 50 개의 홀수 추가 절차를 검색하고 가져 오기 등에 대해 50 개의 홀수 추가 절차를 검색해야합니다.
이 새로운 응용 프로그램 에서이 때문에 개체별로 프로 시저 이름을 그룹화 할 계획이며 절차를 알리는 것 외에는 중복성이 있다고 생각하여 usp를 삭제합니다. 절차 자체.
새로운 형식은 다음과 같습니다
[App]_[Object]_[Action][Process]
App_Tags_AddTag
App_Tags_AddTagRelations
App_Product_Add
App_Product_GetList
App_Product_GetSingle
특히 많은 양의 sproc이있는 경우 나중에 쉽게 찾기 위해 항목을 그룹화하는 데 도움이됩니다.
둘 이상의 객체가 사용되는 위치와 관련하여 대부분의 인스턴스에는 기본 및 보조 객체가 있으므로 기본 인스턴스는 일반 인스턴스에서 사용되고 보조는 프로세스 섹션에서 참조됩니다 (예 : App_Product_AddAttribute).
다음은 SQL Server의 sp_ 접두사 문제에 대한 설명입니다.
접두사 sp_로 명명 된 저장 프로시 저는 마스터 데이터베이스에 저장된 시스템 sproc입니다.
sproc에 접두사를 지정하면 SQL Server는 먼저 마스터 데이터베이스에서 컨텍스트 데이터베이스를 찾은 다음 컨텍스트 데이터베이스를 찾아 불필요한 리소스를 낭비합니다. 또한 사용자가 만든 sproc의 이름이 시스템 sproc과 같은 이름이면 사용자가 만든 sproc이 실행되지 않습니다.
sp_ 접두사는 모든 데이터베이스에서 sproc에 액세스 할 수 있지만 현재 데이터베이스의 컨텍스트에서 실행되어야 함을 나타냅니다.
다음 은 성능 저하에 대한 데모를 포함하는 멋진 설명입니다.
다음 은 Ant가 제공 한 유용한 또 다른 소스입니다.
시스템 헝가리어 (위의 "usp"접두사와 같은)는 나를 헷갈 리게합니다.
비슷한 구조의 서로 다른 데이터베이스간에 많은 저장 프로 시저를 공유하므로 데이터베이스 별 데이터베이스의 경우 데이터베이스 이름 접두사를 사용합니다. 공유 프로 시저에는 접두사가 없습니다. 다른 스키마를 사용하는 것이 그러한 추악한 접두사를 완전히 제거하는 대안 일 수 있다고 생각합니다.
접두어 뒤의 실제 이름은 함수 이름과 거의 다르지 않습니다. 일반적으로 "Add", "Set", "Generate", "Calculate", "Delete"등과 같은 동사 뒤에 "User"와 같은 몇 가지 더 구체적인 명사 ","DailyRevenues "등.
Ant의 의견에 대한 답변 :
- 테이블과 뷰의 차이점은 내용을 액세스하거나 수정하는 사람이 아니라 데이터베이스 스키마를 디자인하는 사람과 관련이 있습니다. 드문 경우에 스키마 특정이 필요한 경우 쉽게 찾을 수 있습니다. 일반적인 SELECT 쿼리의 경우에는 관련이 없습니다. 실제로 테이블과 뷰를 큰 장점으로 취급 할 수 있다고 생각합니다.
- 함수 및 저장 프로 시저와 달리 테이블 또는 뷰의 이름은 동사로 시작하거나 하나 이상의 명사 이외의 이름이 될 가능성이 없습니다.
- A function requires the schema prefix to be called. In fact, the call syntax (that we use, anyway) is very different between a function and a stored procedure. But even if it weren't, the same as 1. would apply: if I can treat functions and stored procedures the same, why shouldn't I?
I have used pretty much all of the different systems over the years. I finally developed this one, which I continue to use today:
Prefix :
- gen - General: CRUD, mostly
- rpt - Report: self-explanatory
- tsk - Task: usually something with procedural logic, run via scheduled jobs
Action Specifier:
Ins - INSERT
Sel - SELECT
Upd - UPDATE
Del - DELETE
(In cases where the procedure does many things, the overall goal is used to choose the action specifier. For instance, a customer INSERT may require a good deal of prep work, but the overall goal is INSERT, so "Ins" is chosen.
Object:
For gen (CRUD), this is the table or view name being affected. For rpt (Report), this is the short description of the report. For tsk (Task) this is the short description of the task.
Optional Clarifiers:
These are optional bits of information used to enhance the understanding of the procedure. Examples include "By", "For", etc.
Format:
[Prefix][Action Specifier][Entity][Optional Clarifiers]
Examples of procedure names:
genInsOrderHeader
genSelCustomerByCustomerID
genSelCustomersBySaleDate
genUpdCommentText
genDelOrderDetailLine
rptSelCustomersByState
rptSelPaymentsByYear
tskQueueAccountsForCollection
TableName_WhatItDoes
Comment_GetByID
Customer_List
UserPreference_DeleteByUserID
No prefixes or silly hungarian nonsense. Just the name of the table it's most closely associated with, and a quick description of what it does.
One caveat to the above: I personally always prefix all my autogenerated CRUD with zCRUD_ so that it sorts to the end of the list where I don't have to look at it.
Starting a stored procedure name withsp_
is bad in SQL Server because the system sprocs all start with sp_. Consistent naming (even to the extent of hobgoblin-dom) is useful because it facilititates automated tasks based on the data dictionary. Prefixes are slightly less useful in SQL Server 2005 as it supports schemas, which can be used for various types of namespaces in the way that prefixes on names used to. For example, on a star schema, one could have dim and fact schemas and refer to tables by this convention.
For stored procedures, prefixing is useful for the purpose of indentifying application sprocs from system sprocs. up_
vs. sp_
makes it relatively easy to identify non-system stored procedures from the data dictionary.
I always encapsulate the stored procedures in packages (I'm using Oracle, at work). That will reduce the number of separate objects and help code reuse.
The naming convention is a matter of taste and something you should agree with all the other developers at project start.
for small databases, i use uspTableNameOperationName, e.g. uspCustomerCreate, uspCustomerDelete, etc. This facilitates grouping by 'main' entity.
for larger databases, add a schema or subsystem name, e.g. Receiving, Purchasing, etc. to keep them grouped together (since sql server likes to display them alphabetically)
i try to avoid abbreviations in the names, for clarity (and new people on the project don't have to wonder what 'UNAICFE' stands for because the sproc is named uspUsingNoAbbreviationsIncreasesClarityForEveryone)
I currently use a format which is like the following
Notation:
[PREFIX][APPLICATION][MODULE]_[NAME]
Example:
P_CMS_USER_UserInfoGet
I like this notation for a few reasons:
- starting with very simple Prefix allows code to be written to only execute objects beggining with the prefix (to reduce SQL injection, for example)
- in our larger environment, multiple teams are working on different apps which run of the same database architecture. The Application notation designates which group owns the SP.
- The Module and Name sections simply complete the heirarchy. All names should be able to be matched to Group/App, Module, Function from the heirarchy.
I always use:
usp[Table Name][Action][Extra Detail]
Given a table called "tblUser", that gives me:
- uspUserCreate
- uspUserSelect
- uspUserSelectByNetworkID
The procedures are alphabetically sorted by table name and by functionality, so it's easy to see what I can do to any given table. Using the prefix "usp" lets me know what I'm calling if I'm (for example) writing a 1000-line procedure that interacts with other procedures, multiple tables, functions, views and servers.
Until the editor in the SQL Server IDE is as good as Visual Studio I'm keeping the prefixes.
application prefix_ operation prefix_ description of database objects involved (minus the spaces between underscores - had to put spaces in for them to appear).
operation prefixes we use -
- “get” – returns a recordset
- “ins” – inserts data
- “upd” – updates data
- “del” – deletes data
e.g
wmt_ ins _ customer _details
"workforce management tool, insert details into customer table"
advantages
All stored procedures relating to the same application are grouped together by name. Within the group, stored procedures that carry out the same kind of operation (e.g. inserts, updates, etc.) are grouped together.
This system works well for us, having approx. 1000 stored procedures in one database off the top of my head.
Haven't come across any disadvantages to this approach so far.
GetXXX - Gets XXX based on @ID
GetAllXXX - Gets all XXX
PutXXX - Inserts XXX if passed @ID is -1; else updates
DelXXX - Deletes XXX based on @ID
I think the usp_ naming convention does nobody any good.
In the past, I've used Get/Update/Insert/Delete prefixes for CRUD operations, but now since I use Linq to SQL or the EF to do most of my CRUD work, these are entirely gone. Since I have so few stored procs in my new applications, the naming conventions no longer matter like they used to ;-)
For the current, application I am working on, we have a prefix that identifies the application name (four lowercase letters). The reason for this is that our application must be able to co-exist with a legacy application in the same database, so the prefix is a must.
If we did not have the legacy constraint, I am quite sure that we would not be using a prefix.
After the prefix we usually start the SP name with a verb that describes what the procedure does, and then the name of the entity that we operate on. Pluralization of the entity name is allowed - We try to emphasize readability, so that it is obvious what the procedure does from the name alone.
Typical stored procedure names on our team would be:
shopGetCategories
shopUpdateItem
I don't think it really matters precisely what your prefix is so long as you're logical and consistent. Personally I use
spu_[action description][process description]
where action description is one of a small range of typical actions such as get, set, archive, insert, delete etc. The process description is something short but descriptive, for example
spu_archiveCollectionData
or
spu_setAwardStatus
I name my functions similarly, but prefix with udf_
I have seen people attempt to use pseudo-Hungarian notation for procedure naming, which in my opinion hides more than it reveals. So long as when I list my procedures alphabetically I can see them grouped by functionality then for me that seems to be the sweet spot between order and unnecessary rigour
Avoid sp_* in SQl server coz all system stored prcedures begins with sp_ and therefore it becomes more harder for the system to find the object corresponding to the name.
So if you begin with something other than sp_ things become easier.
So we use a common naming of Proc_ to begin with. That makes it easier to identify the procedures if presented with one big schema file.
Apart from that we assign a prefix that identify the function. Like
Proc_Poll_Interface, Proc_Inv_Interface
etc.
This allows us to find all stored procs which does the job of POLL vs that does Inventory etc.
Anyhow the prefix system depends on your problem domain. But al said and done something similar ought to be present even if it be just to allow people to quicly locate the stored procedure in the explorere drop down for editing.
other eg's of function.
Proc_Order_Place
Proc_order_Delete
Proc_Order_Retrieve
Proc_Order_History
We followed the function based naming coz Procs are akin to code / function rather than static objects like tables. It doesnt help that Procs might work with more than one table.
If the proc performed more functions than can be handled in a single name, it means your proc is doing way much more than necessary and its time to split them again.
Hope that helps.
I joined late the thread but I want to enter my reply here:
In my last two projects there are different trends like, in one we used:
To get Data : s<tablename>_G
To delete Data : s<tablename>_D
To insert Data : s<tablename>_I
To update Data : s<tablename>_U
This naming conventions is also followed in front-end by prefixing the word dt.
Example:
exec sMedicationInfo_G
exec sMedicationInfo_D
exec sMedicationInfo_I
exec sMedicationInfo_U
With the help of above naming conventions in our application we have a good and easy to remember names.
While in second project we used the same naming conventions with lill difference:
To get Data : sp_<tablename>G
To delete Data : sp_<tablename>D
To insert Data : sp_<tablename>I
To update Data : sp_<tablename>U
Example:
exec sp_MedicationInfoG
exec sp_MedicationInfoD
exec sp_MedicationInfoI
exec sp_MedicationInfoU
참고URL : https://stackoverflow.com/questions/238267/what-is-your-naming-convention-for-stored-procedures
'programing tip' 카테고리의 다른 글
인라인 CSS에서 CSS : before 및 : after 유사 요소를 사용합니까? (0) | 2020.07.14 |
---|---|
NSCache를 사용하는 방법 (0) | 2020.07.14 |
git은 파일 해시를 어떻게 계산합니까? (0) | 2020.07.14 |
초기 커밋을 참조하는 방법? (0) | 2020.07.14 |
numpy를 가져온 후 멀티 프로세싱에서 단일 코어 만 사용하는 이유는 무엇입니까? (0) | 2020.07.14 |