本篇來聊聊如何書寫漂亮、整潔、優(yōu)雅的SQL腳本,下面這些是我個(gè)人總結(jié)、整理出來的。姑且做個(gè)拋磚引玉吧,呵呵,歡迎大家一起來討論。
我們首先來看看一段創(chuàng)建數(shù)據(jù)表的腳本(如下所示),你是否覺得有什么不妥或是不足呢?如果是你,你怎樣書寫呢?
- CREATE TABLE [dbo].[TableDataDictionary](
- [TableID] [int] IDENTITY(1,1) NOT NULL,
- [IpAddress] [nvarchar](15) NOT NULL,
- [DataBaseName] [nvarchar](35) NOT NULL,
- [TableName] [nvarchar](35) NOT NULL,
- [Description] [nvarchar](150) NULL,
- CONSTRAINT [PK_TableDataDictionary] PRIMARY KEY([Tableid])
- )
可能你也沒有覺得它有什么不妥,因?yàn)槟阋恢倍际沁@樣書寫哦。而且更混亂、更雜的的腳本你也見過,也可能習(xí)慣了;那么來看看下面的腳本,
- USE [Test];
- GO
-
- IF OBJECT_ID(N'TableDataDictionary') IS NULL
- CREATE TABLE [dbo].[TableDataDictionary]
- (
- [TableID] INT IDENTITY(1,1) NOT NULL,
- [IpAddress] NVARCHAR(15) NOT NULL,
- [DataBaseName] NVARCHAR(35) NOT NULL,
- [TableName] NVARCHAR(35) NOT NULL,
- [Description] NVARCHAR(150) NULL,
- CONSTRAINT [PK_TableDataDictionary] PRIMARY KEY([Tableid])
- );
- ELSE
- PRINT 'This table have been exist in database';
- GO
上面兩段腳本比起來,你是否覺得下面的更美觀、優(yōu)雅呢?
接下來我們來看看四段申明變量的腳本,自己可以對比
(一)
- DECLARE @PayType VARCHAR(50), @Rate FLOAT, @FeeRate FLOAT ,@OtheFee FLOAT;
- DECLARE @StartDate DATETIME, @EndDate DATETIME;
- DECLARE @CmdSql NVARCHAR(MAX);
- DECLARE @MyCardBillFee FLOAT, @MyCardFee FLOAT;
---------------------------------------------------------------------------------------------------------
(二)
- DECLARE @PayType VARCHAR(50);
- DECLARE @Rate FLOAT;
- DECLARE @FeeRate FLOAT;
- DECLARE @OtheFee FLOAT;
- DECLARE @StartDate DATETIME;
- DECLARE @EndDate DATETIME;
- DECLARE @CmdSql NVARCHAR(MAX);
- DECLARE @MyCardBillFee FLOAT;
- DECLARE @MyCardFee FLOAT;
---------------------------------------------------------------------------------------------------------
(三)
- DECLARE @PayType VARCHAR(50);
- DECLARE @Rate FLOAT;
- DECLARE @FeeRate FLOAT;
- DECLARE @MyCardFee FLOAT;
- DECLARE @OtheFee FLOAT;
- DECLARE @MyCardBillFee FLOAT;
- DECLARE @StartDate DATETIME;
- DECLARE @EndDate DATETIME;
- DECLARE @CmdSql NVARCHAR(MAX);
--------------------------------------------------------------------------------------------------------
(四)
- DECLARE
- @PayType AS VARCHAR(50);
- @Rate AS FLOAT;
- @FeeRate AS FLOAT;
- @MyCardFee AS FLOAT;
- @OtheFee AS FLOAT;
- @MyCardBillFee AS FLOAT;
- @StartDate AS DATETIME;
- @EndDate AS DATETIME;
- @CmdSql AS NVARCHAR(MAX);
-------------------------------------------------------------------------------------------------------
如果是你,你愿意運(yùn)用哪種書寫格式呢? 個(gè)人覺得(一)寫得極極糟糕,不僅閱讀不方便、而且也不方便注視。(二)則是我以前習(xí)慣書寫的格式,一來沒有注視、二來看起來沒有(三)、(四)美觀、大方。
存儲(chǔ)過程、函數(shù)頭部注視的樣式(個(gè)人曾今用過的樣式):
(一)
--======================================================================================
-
-
-
-
--======================================================================================
-- 2010-08-12 : 修改....增加........
-- 2010-08-13 : 修改....增加.......
--=====================================================================================
Function 簡要描述存儲(chǔ)過程、函數(shù)功能。
Desctiption 詳細(xì)描述存儲(chǔ)過程、函數(shù)功能,以及參數(shù)、輸出結(jié)果描述
(二)
--======================================================================================
-
-
-
-
-
-
-
--=======================================================================================
(三)
- /**************************************************************************************************************
- Auhtor : Kerry
- Create Date : 2010-08-12
- Modified Date :
- Modified Content :
- Description : 如何書寫漂亮、優(yōu)雅的SQL腳本
- **************************************************************************************************************/
( 四)
-
-
-
-
-
使用MSSMS新建存儲(chǔ)過程,它自動(dòng)生成的樣式
個(gè)人覺得(一) >= (二) > (三) > (四) ,不知道大家有沒有更好的格式推薦。
下面看看這樣一段腳本,一眼就覺得有點(diǎn)糟糕,其實(shí)實(shí)際開發(fā)中腳本比這個(gè)可能復(fù)雜得多,頭痛吧
- select PermissionID from Permission where resourceid=
- ( select top 1 resourceid from [Resource] where resourcename=@resourcename) and
- actionid=(select top 1 actionid from [Action] where actionname=@actionname)
- AND SchemaId in (SELECT SchemaId FROM dbo.BindToSchema WHERE DcUserID=@UserID)
首先就應(yīng)該統(tǒng)一關(guān)鍵字大小寫,不要一部分大寫、一部分小寫。然后從結(jié)構(gòu)上面調(diào)整。 可能每個(gè)人的審美觀、習(xí)慣的格式不同,這個(gè)無所謂,也沒有必要統(tǒng)一。 但是你書寫出來的腳本至少要結(jié)構(gòu)清晰,一目了然。不要讓別人費(fèi)很大的勁去調(diào)整格式,然后才能理解它的邏輯,如果寫出上面或是比上面更糟糕的腳本,我想項(xiàng)目經(jīng)理真應(yīng)該教訓(xùn)教訓(xùn)你。這樣只會(huì)給后來維護(hù)的人痛苦不堪(實(shí)際開發(fā)中可能比這糟糕十倍呢,想必很多人是深受其害啊)
- SELECT Permission FROM Permission
- WHERE
- resourceid =( SELECT TOP 1 resourceid FROM [Resource] WHERE resourcename=@resourcename)
- AND actionid =(SELECT TOP 1 actionid FROM [Action] WHERE actionname=@actionname)
- AND SchemaId IN (SELECT SchemaId FROM dbo.DcUserBindToSchema WHERE DcUserID=@UserID)
動(dòng)態(tài)組合語句是否讓你的腳本看起來林亂不堪啊,你有沒有試過讓其在某些方面看起來美觀點(diǎn)、優(yōu)雅點(diǎn)啊、
- 'SELECT Order_ID = @OrderID, CampaignCode= @CampaignCode, ProductCode = @ProductCode, StartDate= SpotDate,
- EndDate = EndDate, StartTime= Media_StartTime, EndTime = Media_EndTime, Duration = (CASE WHEN Media_Duration IS NULL OR ELSE Media_Duration END), Adformat= Media_Adformat , Color = Media_Color ,
- Plan_Insertion_ID = Plan_Insertion_ID
那下面書寫格式是不是美觀、整潔些呢
- SELECT
- Order_ID = @OrderID
- , CampaignCode = @CampaignCode
- , ProductCode = @ProductCode
- , StartDate = SpotDate
- , EndDate = EndDate
- , StartTime = Media_StartTime
- , EndTime = Media_EndTime
- , Adformat = Media_Adformat
- , Color = Media_Color
- , Impression = Media_Impression
- , Location = Media_Location
- , Material = Media_Material
- , Position = Media_Position
- , Program = Media_Program
- , Scale = Media_Scale
- , Size = Media_Size
- , SpotType = Media_SpotType
- , URL = Media_URL
- , ScheduleNo = ScheduleNo
- , Plan_Insertion_ID = Plan_Insertion_ID
- , Position = Media_Position
- '
怎么樣是否覺得下面的”清新脫俗“,眼前一亮啊,呵呵,不是在說美女啊??纯次乙郧耙粋€(gè)同事寫的吧,我只截取了一部分。
寫著覺得有點(diǎn)天馬行空、不著邊際了,其實(shí)這個(gè)話題有點(diǎn)大,而且和個(gè)人習(xí)慣、審美觀有莫大聯(lián)系,所謂眾口難調(diào),不過有幾點(diǎn)應(yīng)該是一致的:
1:書寫腳本的時(shí)候,多用空格、Tab鍵,不要讓代碼擁擠,雜糅在一起。
2:讓代碼看起來覺得舒服,一目了然,不要一看就覺得頭痛,要細(xì)細(xì)看上好久,才了解邏輯結(jié)構(gòu)
3:讓代碼看起來整潔、優(yōu)美。凌亂不堪是大忌。
4:總結(jié)、學(xué)習(xí)一些書寫漂亮的格式。
限于篇幅,下面給出一些我見過的、寫的比較優(yōu)雅的腳本,大家也可以貼出自己寫得優(yōu)美的代碼,一起學(xué)習(xí)探討。、
-
- SET @sql =
- N'SET @result = ' + @newline +
- N' STUFF(' + @newline +
- N' (SELECT N'','' + '
- + N'QUOTENAME(pivot_col) AS [text()]' + @newline +
- N' FROM (SELECT DISTINCT('
- + @on_cols + N') AS pivot_col' + @newline +
- N' FROM' + @query + N') AS DistinctCols' + @newline +
- N' ORDER BY pivot_col' + @newline +
- N' FOR XML PATH('''')),' + @newline +
- N' 1, 1, N'''');'
-
- EXEC sp_executesql
- @stmt = @sql,
- @params = N'@result AS NVARCHAR(MAX) OUTPUT',
- @result = @cols OUTPUT;
-
-
- SET @sql =
- N'SELECT *' + @newline +
- N'FROM' + @newline +
- N' ( SELECT ' + @newline +
- N' ' + @on_rows + N',' + @newline +
- N' ' + @on_cols + N' AS pivot_col,' + @newline +
- N' ' + @agg_col + N' AS agg_col' + @newline +
- N' FROM ' + @newline +
- N' ' + @query + @newline +
- N' ) AS PivotInput' + @newline +
- N' PIVOT' + @newline +
- N' ( ' + @agg_func + N'(agg_col)' + @newline +
- N' FOR pivot_col' + @newline +
- N' IN(' + @cols + N')' + @newline +
- N' ) AS PivotOutput;'
代碼
- DECLARE
- @schemaname AS NVARCHAR(128),
- @tablename AS NVARCHAR(128),
- @colname AS NVARCHAR(128),
- @sql AS NVARCHAR(805);
-
- SET @schemaname = N'dbo';
- SET @tablename = N'Orders';
- SET @colname = N'CustomerID';
- SET @sql = N'SELECT COUNT(DISTINCT '
- + QUOTENAME(@colname) + N') FROM '
- + QUOTENAME(@schemaname)
- + N'.'
- + QUOTENAME(@tablename)
- + N';';
-
- EXEC(@sql);
原文標(biāo)題:如何書寫優(yōu)雅、漂亮的SQL腳本?
鏈接:http://www.cnblogs.com/kerrycode/archive/2010/08/16/1800334.html