How big is an nvarchar(max) as far as ADO is concerned?

徘徊边缘 提交于 2019-12-11 01:15:42

问题


i am trying to use a parameterized query against ADO:

INSERT INTO Foo (Name, Value) VALUES(@name, @value)

In SQL Server the Name column is a varchar type. The Value column is an nvarchar(max).

What size do i pass when creating a parameter when i don't know, or want to specify, the size?

procedure SaveTheThing(Connection: TADOConnection);
var
   sql: WideString;
   cmd: _Command;
begin
   sql := 'INSERT INTO Foo (Name, Value) VALUES(@name, @value)';

   cmd := CoCommand.Create;
   cmd.Set_ActiveConnection(Connection.ConnectionObject);
   cmd.Set_CommandType(adCmdText);
   cmd.Set_CommandText(sql);

   //and now add the parameters
   cmd.Parameters.Append(
         cmd.CreateParameter('@name', adVarChar, adParamInput, -1, filename)
   );
   cmd.Parameters.Append(
         cmd.CreateParameter('@value', adVarWChar, adParamInput, -1, GetXmlToWideString)
   );

   cmd.Execute({out}recordsAffected, EmptyParam, adCmdSomeThatDoesntCauseAnExcetpion or adExecuteNoRecords);
end;

The simple alternative was going to be:

sql := 'INSERT INTO Foo (Name, Value)'#13#10+
       'VALUES (+QuotedStr(filename)+', '+QuotedStrW(GetXmlToWideString)+')';

and be done already. But i thought i'd burn a few days trying to make parameterized queries a viable solution, and avoid having to write a QuotedStrW.


回答1:


You can use the -1 value in the size of a ADO parameter without problems.

Try this sample code , which insert a 2MB string in the Value column

var
   sql: WideString;
   cmd: _Command;
   recordsAffected : OleVariant;
begin
   sql := 'INSERT INTO Foo (Name, Value) VALUES(?, ?)';
   cmd := CoCommand.Create;
   cmd.Set_ActiveConnection(Connection.ConnectionObject);
   cmd.Set_CommandType(adCmdText);
   cmd.Set_CommandText(sql);

   //and now add the parameters
   cmd.Parameters.Append(cmd.CreateParameter('@name', adVarChar, adParamInput, -1, 'AfileName'));
   cmd.Parameters.Append(cmd.CreateParameter('@value', adVarWChar, adParamInput, -1, StringOfChar('#', 2*1024*1024)));
   cmd.Execute({out}recordsAffected, EmptyParam, adExecuteNoRecords);
end;



回答2:


You can use my answer on your other post:

"Must declare the variable @myvariable" error with ADO parameterized query

to use parameters and parameter by name. Try to avoid using _Command, but use TADOCommand because it is more friendly (and simpler to code too). You can assign parameter to a value by using:

Parameters.ParamByName('xxxx').value := someValue. 

Of course someValue data type must correspond to your SQL server column data type definition.



来源:https://stackoverflow.com/questions/10723757/how-big-is-an-nvarcharmax-as-far-as-ado-is-concerned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!