首页 > 解决方案 > vb.net vbcrlf、environment.newline & vbcr 不工作

问题描述

VB.Net代码

Dim sTest As String = "QueryLine1" & vbCrLf & "QueryLine2"

电流输出

"QueryLine1" & vbCrLf & "QueryLine2"

我想看看

查询行1

查询行2

SQL 查询

declare @now date,@dob date, @now_i int,@dob_i int, @days_in_birth_month int
declare @years int, @months int, @days int
set @now = '2013-02-28' 
set @dob = '2012-02-29' -- Date of Birth

set @now_i = convert(varchar(8),@now,112) -- iso formatted: 20130228
set @dob_i = convert(varchar(8),@dob,112) -- iso formatted: 20120229
set @years = ( @now_i - @dob_i)/10000
-- (20130228 - 20120229)/10000 = 0 years

set @months =(1200 + (month(@now)- month(@dob))*100 + day(@now) - day(@dob))/100 %12
-- (1200 + 0228 - 0229)/100 % 12 = 11 months

set @days_in_birth_month = day(dateadd(d,-1,left(convert(varchar(8),dateadd(m,1,@dob),112),6)+'01'))
set @days = (sign(day(@now) - day(@dob))+1)/2 * (day(@now) - day(@dob))
          + (sign(day(@dob) - day(@now))+1)/2 * (@days_in_birth_month - day(@dob) + day(@now))
-- ( (-1+1)/2*(28 - 29) + (1+1)/2*(29 - 29 + 28))
-- Explain: if the days of now is bigger than the days of birth, then diff the two days
--          else add the days of now and the distance from the date of birth to the end of the birth month 
select @years,@months,@days -- 0, 11, 28 

将其存储在变量中并执行存储的 sql 查询结果为空白时。因为输入标记被注意存储在变量中。

如果您将上述 sql 查询复制粘贴到 sql 查询窗口中,那么您将得到结果。但是当将查询存储在 vb.net 变量中并执行查询时没有任何结果。

我试图用一个小例子来强调这个问题,这就是为什么从一小段代码开始。

标签: vb.net

解决方案


您所说的正在发生的事情仍然无法真正发生,但无论如何,这甚至都没有关系。如果您想要编写多行 SQL 查询,那么您根本不需要使用字符串连接。如果您使用的是 VB 2015(或更高版本),那么您实际上可以编写多行String文字,例如

        Dim query = "SELECT *
FROM MyTable
WHERE ID = 1"

如果您愿意,您可以对其进行格式化以使文本对齐,因为 SQL 不关心空格:

Dim query = "SELECT *
             FROM MyTable
             WHERE ID = 1"

如果您使用的是旧版本的 VB,那么您可以使用 XML 文字:

        Dim sql = <sql>
SELECT *
FROM MyTable
WHERE ID = 1
                  </sql>
        Dim query = sql.Value

同样,如果需要,您可以使用空格进行格式化:

Dim sql = <sql>
            SELECT *
            FROM MyTable
            WHERE ID = 1
          </sql>
Dim query = sql.Value

如果您查看query使用调试器的值,那么您仍然应该看到与现在相同的东西,如果它在某个无法显示多行Strings但实际值将完全符合它的地方。


推荐阅读