0

我在 SQL Server 2008 中有一个查询。

SELECT
    CONVERT(char(80), i.InvDate,3) AS InvDate,
    i.InvoiceNo,
    i.TaxAmount + i.SubTotal AS Amount,
    '' AS Payment,
    pd.GivenName
FROM
dbo.Invoice i
    INNER JOIN dbo.PatientDetails pd ON (pd.MedicalRecordID = i.MedicalRecordID)
    WHERE (InvDate >= CONVERT(datetime, '16/10/2012', 105)) AND 
(InvDate <= CONVERT(datetime, '16/10/2012', 105))

输出:

在此处输入图像描述

当我尝试将其放入 C# 时,它显示“从字符串转换日期和/或时间时转换失败。”


信息:16/10/2012 是我试图插入查询以确保它运行的示例日期。这是一个旧程序,这就是它从字符串转换的原因。我很确定它与日期时间格式有关。看看http://www.sqlusa.com/bestpractices/datetimeconversion/。但我不能把手指穿过它。

SqlCommand objCmd = new SqlCommand("SELECT CONVERT(char(80), i.InvDate,3) 

AS InvDate,

i.InvoiceNo, i.TaxAmount + i.SubTotal AS Amount,'' AS Payment,pd.GivenName 

FROM

dbo.Invoice i INNER JOIN dbo.PatientDetails pd

ON 
(pd.MedicalRecordID = i.MedicalRecordID)

WHERE

(InvDate >= CONVERT(datetime, 'dd/MM/yyyy', 105)) 

AND 

(InvDate <= CONVERT(datetime, 'dd/MM/yyyy', 105))", objConn);



        SqlDataReader objReader;
        objReader = objCmd.ExecuteReader();

        System.IO.FileStream fs = new System.IO.FileStream("C:\\CMSExportedData\\Sales-" + 
DateTime.Now.ToString("dd-MM-yyyy") + ".txt", System.IO.FileMode.Create);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fs,   
System.Text.Encoding.Default);
4

3 回答 3

1

你的没有什么问题SQL code。如果您有多行字符串,您只需要在命令中的双引号之前添加@逐字字符串文字)。

SqlCommand objCmd = new SqlCommand(@"SELECT CONVERT(char(80), i.InvDate,3) AS InvDate,
               i.InvoiceNo, 
               i.TaxAmount +  i.SubTotal AS Amount,'' AS Payment,pd.GivenName 
FROM    dbo.Invoice i INNER JOIN dbo.PatientDetails pd
            ON (pd.MedicalRecordID = i.MedicalRecordID)
WHERE   (InvDate >= CONVERT(datetime, 'dd/MM/yyyy', 105)) AND 
        (InvDate <= CONVERT(datetime, 'dd/MM/yyyy', 105))", objConn);
于 2012-10-16T05:01:46.020 回答
1

CONVERT(datetime, 'dd/MM/yyyy', 105)正在尝试将文字文本dd/MM/yyyy转换为datetime- 这永远不会起作用。

SqlCommand objCmd = new SqlCommand(@"SELECT CONVERT(char(80), i.InvDate,3) 
AS InvDate,
i.InvoiceNo, i.TaxAmount + i.SubTotal AS Amount,'' AS Payment,pd.GivenName 
FROM
dbo.Invoice i INNER JOIN dbo.PatientDetails pd
ON 
(pd.MedicalRecordID = i.MedicalRecordID)
WHERE
(InvDate >= @StartDate) 
AND 
(InvDate <= @EndDate)", objConn);

objCmd.Parameters.AddWithValue("@StartDate",/* some C# expression that gives you the start date, as a DateTime value */);
objCmd.Parameters.AddWithValue("@EndDate",/* some C# expression that gives you the end date, as a DateTime value */);

您必须填写上面最后两行中的注释部分。猜测一下,根据您之前的问题,它们可能是dtpFrom.Valueand dtpTo.Value

于 2012-10-16T06:41:25.283 回答
0

我更愿意将查询移动到存储过程并从您的数据映射器类中调用存储过程。

于 2012-10-16T05:06:05.123 回答