SQL server - Insert string record containing backslash

左心房为你撑大大i 提交于 2021-02-11 09:52:42

问题


I'm trying to insert a record in the table where one of the column has following value.

\\\\a\\b\\c

Database DataProvider = new SqlDatabase(connectionstring);  
DataProvider.ExecuteNonQuery("sprocname",
                    Id,
                    qText,
                );  

Here, qText has above value. After execution, the value gets added in the table as \ (single backslash) only.

If I try to insert the record manually in the table,

INSERT INTO mytbl(id, q) VALUES
 (0, '\\\\a\\b\\c')

proper value gets inserted. Any reason why this is happening? Am I missing anything here?

UPDATE

It seems that whatever my string is, only it's first letter getting inserted in that column! Not sure why. The datatype of the column is varchar(max)

Ex.

for qText = 'abc', then column has value `a`
for qText = '\\\\a\\b\\c', then column has value `\`

回答1:


Backslash is an escape sequence character, so two backslashes will be interpreted as one backslash. If you want to keep your backslashes as it is in this case use verbatim string literal which adds @ at the beginning of the string literal.

var qText = @"\\\\a\\b\\c";



回答2:


While storing the \ in a string variable, you need to add it as an escape sequence "\\"

So, if we write

String qText = "\\"

the value of qText will be \

Therefore to store \\\\a\\b\\c, you should assign double the number of \.

String qText = "\\\\\\\\a\\\\b\\\\c"

This way when used, the value of qText will be \\\\a\\b\\c




回答3:


The issue was in the stored procedure. The input parameter for the procedure was varchar, but length was not specified.



来源:https://stackoverflow.com/questions/36687741/sql-server-insert-string-record-containing-backslash

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