将SQL Server查询转换为Delphi语法

时间:2011-06-25 03:00:24

标签: delphi delphi-2010 delphi-xe

这是原始的SQL服务器查询:

use HIS

SELECT
room_type,rate_start_date,rate_end_date,rate
, DATEDIFF(DAY,case when rate_end_date < '2011.08.21'
then '2011.08.19'
else rate_start_date
end,
case when rate_start_date > '2011.08.19'
then '2011.08.21'
else rate_end_date
end
) AS days FROM room_rates
WHERE room_type = 'DBLMS' AND rate_start_date <= '2011.08.21'
AND rate_end_date > '2011.08.19'

我将它转换为Delphi SQL:

procedure TForm1.Button1Click(Sender: TObject);
begin
uniQuery1.Close;
uniQuery1.SQL.Clear;
uniQuery1.SQL.Add('SELECT room_type,rate_start_date,rate_end_date,rate,');
uniQuery1.SQL.Add('DATEDIFF(DAY,case when rate_end_date < 2011.08.21 then 2011.08.19 else rate_start_date end,');
uniQuery1.SQL.Add('case when rate_start_date > 2011.08.19');
uniQuery1.SQL.Add('then 2011.08.21 else rate_end_date end) AS days FROM room_rates');
uniQuery1.SQL.Add('WHERE room_type = DBLMS AND rate_start_date <= 2011.08.21');
uniQuery1.SQL.Add('AND rate_end_date > 2011.08.19');
uniQuery1.Open;
end;

但是我收到'无效的列名称'DBLMS''

我在这里缺少什么? DBLMS不是专栏。

1 个答案:

答案 0 :(得分:10)

你没有引用你的sql语句中的字符串尝试重写你的代码:

procedure TForm1.Button1Click(Sender: TObject);
begin
  uniQuery1.Close;
  uniQuery1.SQL.Clear;
  uniQuery1.SQL.Add('SELECT room_type,rate_start_date,rate_end_date,rate,');
  uniQuery1.SQL.Add('DATEDIFF(DAY,case when rate_end_date < ''2011.08.21'' then ''2011.08.19'' else rate_start_date end,');
  uniQuery1.SQL.Add('case when rate_start_date > ''2011.08.19''');
  uniQuery1.SQL.Add('then ''2011.08.21'' else rate_end_date end) AS days FROM room_rates');
  uniQuery1.SQL.Add('WHERE room_type = ''DBLMS'' AND rate_start_date <= ''2011.08.21''');
  uniQuery1.SQL.Add('AND rate_end_date > ''2011.08.19''');
  uniQuery1.Open;
end;

作为附加建议,尝试使用参数而不是字符串文字,这样您将保护您的代码免受SQL注入和其他优点。查看这篇文章Using Parameters in Queries