ricky32
ricky32

Reputation: 107

SQL server - Insert string record containing backslash

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 `\`

Upvotes: 3

Views: 17493

Answers (3)

ricky32
ricky32

Reputation: 107

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

Upvotes: 0

asktonishant
asktonishant

Reputation: 303

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

Upvotes: 2

Ramin
Ramin

Reputation: 207

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";

Upvotes: 5

Related Questions