简体   繁体   中英

Getting Error in CreateTableCommand.ExecuteNonQuery();

This is the query in which im getting error

CreateTableCommand.CommandText = "BACKUP DATABASE Test" +
                             "TO  DISK = 'C:\backup\t1.bak'" + 
                                 "WITH " +
                             "NOFORMAT, " +
                             "COMPRESSION," +
                             "NOINIT,  " +
                             "NAME = N't1-Full Database Backup'," + 
                             "SKIP, " +
                                 "STATS = 10;";

and the error is "Incorrect syntax near 'DISK'." but if i run run that query ms sql server 2008 its work fine but when i try to use that in my C# application it gave error pls help me out

Add another space after Test , your SQL is built to ... TestTO DISK ... .

string line2 = "BACKUP DATABASE Test ";

As Onots pointed out, you should also escape some characters properly ( \\ introduces an escape sequence, \\ itself is escaped as \\\\ ):

string line2 = "TO  DISK = \'C:\\backup\\t1.bak\'";

See also MSDN: string (C# Reference) for details.

For SQL statements, it's easier to use a Verbatim string literal for the whole query rather than concatenating fragments. Eg

CreateTableCommand.CommandText = @"
BACKUP DATABASE Test
TO  DISK = 'C:\backup\t1.bak'
WITH 
NOFORMAT, 
COMPRESSION,
NOINIT,
NAME = N't1-Full Database Backup',
SKIP, 
STATS = 10;
";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM