Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing NULL value into parameterized delphi SQL server query

I am trying to pass in a null value to a TSQLDataset parameter. The query has the form:

Query_text:='MERGE INTO [Table] 
             USING (VALUES (:A,:B)) AS Source (Source_A, Source_B)
             ....
             WHEN MATCHED THEN 
             UPDATE SET A = :A
             WHEN NOT MATCHED THEN
             INSERT(A, B) VALUES (:A,:B);

SQL_dataset.CommandType:=ctQuery; 
SQL_dataset.CommandText:=Query_text;

SQL_dataset.ParamByName('A').AsString:='A';  
SQL_dataset.ParamByName('B').AsString:={ COULD BE NULL, OR A STRING };    

SQL_dataset.ExecSQL;

Parameter B is nullable, but is also a foreign key. If the user enters something in this field, then B must be validated against values in another table. If it is blank then I want it to be ignored. I was passing in '', but this obviously produces a FK violation error.

I tried:

SQL_dataset.ParamByName('B').Value:=Null;

..but then I get a "dbexpress driver does not support the tdbxtypes.unknown data type" error.

I also tried:

SQL_dataset.ParamByName('B').DataType:=ftVariant;
SQL_dataset.ParamByName('B').Value:=Null;

..but then got "dbexpress driver does not support the tdbxtypes.variant data type" error.

Not sure what I am doing wrong, any help would be appreciated. I am currently drawing up a parameter list based on whether the string is populated or not, and this works well; it's just a bit clunky (in my actual query) as there are quite a few parameters to validate.

I am using Delphi XE4 and SQL server 2012.

Update:

Thanks for all the help, your suggestions were right all along, it was something else that produced that 'dbexpress driver' error. I was creating a 'flexible' parameter list in an effort to get around my problem, and this caused the exception:

Parameter_string:='';

If B<>'' then Parameter_string:='B = :B,'

Query_text:='MERGE ...'
            '...'
            'UPDATE SET A = :A, '+Parameter_string+' C = :C' ....

... the idea being that if B is blank then the parameter won't be 'listed' in the query.

This doesn't work, or my implementation of it doesn't work (not sure why, I'm obviously missing a step somewhere).

Anyway, the working code:

Query_text:='MERGE ...'
            '...'
            'UPDATE SET A = :A, B = :B, C = :C' ....

SQL_dataset.CommandType:=ctQuery; 
SQL_dataset.CommandText:=Query_text;

If B<>'' then
begin
  SQL_dataset.ParamByName('B').AsString:='B';
end
else
begin
  SQL_dataset.ParamByName('B').DataType:=ftString;
  SQL_dataset.ParamByName('B').Value:=Null;
end;
like image 990
Alex Avatar asked Jun 11 '13 10:06

Alex


1 Answers

what about:

SQL_dataset.ParamByName('B').Clear;

like image 55
pf1957 Avatar answered Sep 28 '22 10:09

pf1957