標籤:
Sql語句使用規範規範內容以及注意事項:
1、查詢時候使用top 10 /top 100 和where 字句控制每次執行SQL 返回的結果集合,在滿足業務需求的同時返回最小的結果。
2、使用資料投影的方式,選擇前端程式需要的資料列,不允許使用select * from dbo.TableA的方式訪問資料庫中的列。
如:select userid , username , sex from dbo.TableA
3、盡量使用預存程序訪問資料庫中的資料。減少直接使用SQL 指令碼訪問資料庫資源。
4、所有的SQL 語句都不允許使用系統資料表和系統欄位,作為判斷商務邏輯或者產生臨時資料的依據。
如:select name from sys.sysobjects where xtype = ‘U’ 來查詢所有的使用者表。
5、編寫長指令碼需要注意縮排和換行,提高SQL指令碼的閱讀性。
如:
--查詢OrdersSelect top 10 OrderID, UserID, ProductIDFrom dbo.OrdersWhere …--插入OrdersInsert into dbo.Orders(OrderID,UserID,ProductID)Values(1,2,3)
6、插入資料的語句需要把插入欄位寫全。
如上:
插入orders樣本,不允許寫成:insert into dbo.orders select 1,2,3
7、SQL 語句調用對象的時候需要加上對象的所有者,如果是預設的所有者,需要加上dbo。
如:
select userid,username from dbo.TableA 不要寫成 select userid,username from TableA
8、如果需求沒有強制要求返回的查詢結果需要排序,SQL指令碼後面不要加上Order By子句。
9、SQL語句如果設計到多表串連查詢的時候,需要用表的別名,而不要使用“表名.列名”的方式。
如:select a.userid,a.username,b.sex From dbo.TableA a Join dbo.TableB b on a.userid = b.userid Where …….錯誤寫法:select TableA.userid,TableA.username,TableB.sex From dbo.TableA Join dbo.TableB on tableA.userid = TableB.userid Where …….
10、在大量資料插入的情況下,把需要插入的資料整合起來一起插入資料庫,會節省很多資源。
如:常規寫法
Insert into dbo.TableA(id,name)Select 1,’aa’Insert into dbo.TableA(id,name)Select 2,’bb’
建議寫法:
Insert into dbo.TableA(id,name)Select 1,’aa’Union allSelect 2,’bb’
建議寫法2:
Insert into dbo.tableA(id,name)Values(1,’aa’),(2,’bbb’)
如:常規寫法:
Update aSet a.userno = a.userno+1From dbo.TableA aWhere a.username = ‘張三’GoUpdate aSet a.userno = a.userno +1From dbo.TableA aWhere a.username = ‘李四’
建議寫法
Update aSet a.userno = a.userno+1From dbo.TableA aWhere a.username in (‘張三’,’李四’)
11、 多表查詢時候需要嚴格限制欄位的別名,以防止SQL解析出現邏輯錯誤。
如:
select OrderID,UserID from dbo.Orders where UserID in (select OrderID from dbo.UserInfo)如果作為子查詢UserInfo中沒有OrderID,SQL會到父查詢中尋找OrderID欄位,導致邏輯錯誤
12、引用的對象名或欄位名,嚴格按照其原始大小寫調用
如:查詢Orders表
不能寫成select orderid,…. From dbo.orders …
要寫成select OrderID,…. From dbo.Orders …
防止資料庫編碼規則更改,導致無法找到對象。
sql server 語句使用規範