园子里关于存储过程的讨论有很多,不少人建议将SQL语句写在程序中,这篇随笔讨论一下SQL语句在程序中的写法。
1
string
strSQL
=
"
SELECT [AddressID], [AddressLine1], [AddressLine2], [City], [StateProvinceID], [PostalCode], [rowguid], [ModifiedDate] FROM [AdventureWorks].[Person].[Address] WHERE City = 'Bothell' ORDER BY AddressID
"
;
这是最普通的一种写法,而且在开发中被广泛采用。
1
string
strSQL
=
"
SELECT
"
+
2 " [AddressID], " +
3 " [AddressLine1], " +
4 " [AddressLine2], " +
5 " [City], " +
6 " [StateProvinceID], " +
7 " [PostalCode], " +
8 " [rowguid], " +
9 " [ModifiedDate] " +
10 " FROM " +
11 " [AdventureWorks].[Person].[Address] " +
12 " WHERE " +
13 " City = 'Bothell' " +
14 " ORDER BY " +
15 " AddressID " ;
16
2 " [AddressID], " +
3 " [AddressLine1], " +
4 " [AddressLine2], " +
5 " [City], " +
6 " [StateProvinceID], " +
7 " [PostalCode], " +
8 " [rowguid], " +
9 " [ModifiedDate] " +
10 " FROM " +
11 " [AdventureWorks].[Person].[Address] " +
12 " WHERE " +
13 " City = 'Bothell' " +
14 " ORDER BY " +
15 " AddressID " ;
16
第二种写法,除了让人开着舒服一点外,没有任何好处。
上图所示的写法要更好一点,可以降低维护难度,提高开发效率,团队开发中应该对这些小细节加以规定。其中,图中标示的第一点可以看看在SQL Server 2005中通过下图菜单生成的SQL语句,但不知道为什么SQL Server 2005的查询编辑器生成的SQL语句还是那么蹩脚。微软完全可以解析SQL语句并使之成为更有利于开发的格式。
如果有两个表进行连接,INNER(LEFT/RIGHT) JOIN等语句也应该写在一行。另外,建议使用更简单的英文别名代替中文表名。
呵呵,很简单吧?如果有更好的书写SQL语句的改进方案,请告诉我。