当我尝试在CmdString
中使用抛出异常时,问题出在变量小时。我不明白为什么在变量小时为字符串时抛出异常。我怎么解决这个问题。我在这里失踪了什么。
string ConString = ConfigurationManager.ConnectionStrings["DbSystem"].ConnectionString;
string CmdString = string.Empty;
DateTime time = DateTime.Now;
string hour = time.Hour.ToString();
using (SqlConnection con = new SqlConnection(ConString))
{
string folderName = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
string folder = Path.Combine(FOLDER_FOR_BACKUP_FILES);
Directory.CreateDirectory(FOLDER_FOR_BACKUP_FILES);
CmdString = @"declare @fileName varchar(100); declare @dbName varchar(100); declare @fileDate varchar(20); set @fileName = '" + folder + @"\'; set @dbName = 'DbSystem'; set @fileDate = convert(varchar(20), getdate(), 105); set @fileName = @fileName + @dbName + ' ' + @fileDate + '-' + " + hour + @" + '.bak'; backup database @dbName to disk = @fileName;";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("*");
sda.Fill(dt);
}
答案 0 :(得分:2)
您应该CONVERT
小时到VARCHAR
:
@fileDate + '-' + CONVERT(VARCHAR(20), " + hour + @") + '.bak';
虽然hour
是应用程序端的字符串,但当它由SQL Server执行时,它是INT
。因此,您需要隐式包含CONVERT
函数。
答案 1 :(得分:1)
因为小时现在是字符串。您可以将CmdString更改为
CmdString = @"declare @fileName varchar(100); declare @dbName varchar(100); declare @fileDate varchar(20); set @fileName = '" + folder + @"\'; set @dbName = 'DbSystem'; set @fileDate = convert(varchar(20), getdate(), 105); set @fileName = @fileName + @dbName + ' ' + @fileDate + '-' + '" + hour + @"' + '.bak'; backup database @dbName to disk = @fileName;";