3

This is the original SQL server query which works:

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'

I converted it to 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;

However I am getting 'Invalid column NAME 'DBLMS''

What am I missing here ? DBLMS is not a column.

1 Answer 1

10

You are no quoting the strings inside of your sql sentence try rewriting your code to this :

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;

As addtional advice , try using parameters instead of string literals, in this way you will protect your code against sql injection beside others advantages. check this article Using Parameters in Queries

Sign up to request clarification or add additional context in comments.

2 Comments

I used your suggestion and replaced dates,room_types with parameters but still DAYS do not show.Interesting...SQL server displays days without problem... Why is this ?
it seems that TMS grid as well as the cxGrid do not want to show the 'days' field while the one from Delphi 8standard built in grid) does. Which is strange indeed....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.