3

目前我将查询放在这样的变量中。

query = @"  select top 1
                u.UserID
            from
                dbo.Users u
            where
                u.SystemUser = 1
                and u.Status = @Status";

这样做的问题是,在换行时缩进会丢失,我必须自己添加。

有人知道更好的方法吗?我知道存储过程是一种可能性(消除了这个缩进问题),但我不确定它们对于纯数据检索是否一定更好。

4

5 回答 5

6

忽略 TSQL 的仇恨者;了解一些 TSQL 本质上没有错!无论如何,我会通过(如果我保持你的格式,这不是我的标准 - 但是......嗯);

                // your existing code at, say, this level
                var query = @"
select top 1
      u.UserID
from
      dbo.Users u
where
      u.SystemUser = 1
      and u.Status = @Status";

                // some more code at, say, this level

通过将 TSQL 保持在左侧,任何缩进等都更容易在 IDE 中完成,但它也使 TSQL 更短,并且在查看跟踪时更容易调试,因为它不是奇怪的 30 左右的字符. 在 the 之前换行select也有助于保持整洁。

Personally, I also find the disjoint between the code indent and the TSQL indent helps find TSQL - and TSQL is pretty important to me, so this is a good thing. And emphasising that we've just switched "world" (for want of a better term) is not harmful, either.

于 2011-08-04T12:40:08.047 回答
3

您至少应该考虑使用 LINQ。它确实有一个学习曲线,但它会给您带来编译器检查查询语法的优势。

您不会说这是否是一个网络应用程序,但如果您从用户输入(例如来自 Web url 或从浏览器发布的数据)中获得任何查询输入,请在发送到之前将用户输入嵌入到字符串中查询引擎也比其他执行查询的方法更容易受到 SQL 注入攻击。

使用实体框架是另一种出色的方法。我最近使用了 Code First 方法,它非常优雅。最后,存储过程也是一个好方法。

于 2011-08-04T12:27:01.143 回答
1

你总是可以这样做:

query = " select top 1"
      + "     u.UserID"
      + " from"
      + "     dbo.Users u"
      + " where"
      + "     u.SystemUser = 1"
      + "     and u.Status = @Status";

至少这样,您的 IDE 将缩进字符串,而不是 SQL。如果你这样做,你必须小心在每一行添加一个前导空格。

更好的选择是使用 LINQ:

result = (from
             u in dbo.Users
         select
             u.userId
         where
             u.SystemUser == 1 &&
             u.Status = @Status
).Take(1)
于 2011-08-04T12:25:23.843 回答
1

首先,SQL 的格式只有在人类能够看到时才重要。

如果您真的想保留缩进,可以将字符串放入资源中(在资源编辑器中使用 SHIFT+ENTER 插入新行)。多亏了 Visual Studio 的魔法,访问资源变得很容易(Properties.Resources.*)。

如果您使用的是 WPF,您还可以使用 XAML 资源。

于 2011-08-04T12:27:22.550 回答
0

或者您可以使用不同的方式来获取您pure data
可以使用 的

stored procedues
LINQ 2 SQL
Entity Framework
ADO.NET

硬编码的 sql 语法并不是最佳实践。

于 2011-08-04T12:25:38.860 回答