Can't concatenate to strings with CHAR(0) at the end

﹥>﹥吖頭↗ 提交于 2021-02-11 12:19:03

问题


The following snippets should demonstrate an issue I've observed in both SQL Server and in my VBScript web application:

SELECT '"Hello World"'
SELECT '"Hello World' + CHAR(0) + '"'

Results:

"Hello World"
"Hello World

Notice that the second result line is missing the final double quote.

I understand that you can't concatenate strings to a NULL value in SQL Server. However, the following snippet reveals that CHAR(0) is not considered NULL as far as SQL Server is concerned.

SELECT ISNULL(CHAR(0), 'CHAR(0) IS CONSIDERED NULL')

Result:


Also, when I read this value from the DB into a variable in VBScript, I'm unable to concatenate to that variable as well.

I'm not a C developer, but I understand that C-style strings are terminated by the null character. Is this relevant? Can someone please help me understand why this is happening in SQL Server and in VBScript?

I can solve my immediate problem by simply replacing all CHAR(0)'s in the offending data, but first I'd like to understand the reason for this and develop a preventative solution.


EDIT: Including some VBScript

testSql = "SELECT '""Hello World' + CHAR(0) + '""' AS TestString"
set resultSet = conn.execute(testSql)
testString = resultSet.Fields.Item("TestString")

testString = testString & "}"

Response.Write testString

Result:

"Hello World

回答1:


SQL server concatenates strings ending in nul characters just fine. See this example:

SELECT len('"Hello World' + CHAR(0) + '"')

Output:

14

SELECT len('"Hello World' + CHAR(0) + '"' + '"Hello World' + CHAR(0) + '"')

Output:

28

The result is the same when you store the string into a CTE or table first.

Its the handling and output in VB that makes it appear as if it does not. Try to print the length of the string your are getting out of SQL in VB.



来源:https://stackoverflow.com/questions/55640331/cant-concatenate-to-strings-with-char0-at-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!