sql-server - ADO 不传递第一个参数值
问题描述
我正在使用 ADO Command对象生成针对 SQL Server 的参数化查询。
如果我生成并提供多个参数,则所有参数值都会传递 -除了第一个参数值。
如果您想象这样的查询:
SELECT ?, ?, ?, ?, ?
并使用 ADO Command 对象提供参数值:
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 1);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 2);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 3);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 4);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 5);
可以使用 Profiler 查看第一个参数值为 null:
exec sp_executesql N'SELECT @P1, @P2, @P3, @P4, @P5',N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int',NULL,2,3,4,5
我用不同的类型、不同的查询、不同的顺序尝试过它。它始终是拒绝提供给数据库服务器的第一个参数。
我可以在调用 Execute 之前确认该参数确实有一个值:
command.Parameters[0].Value
我究竟做错了什么?
- 客户端: Windows Vista、Windows 7、Windows 10
- OLEDB 提供程序: SQLOLEDB、SQLNCLI11、MSOLEDBSQL
- 服务器: SQL Server 2000、SQL Server 2005、SQL Server 2008 R2、SQL Server 2012、SQL Sever 2017
- 编译器:Delphi 5、Delphi XE6、Delphi 10.3 Electric Boogaloo
CMRE
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
ActiveX,
ComObj,
ADOint,
Variants;
procedure Main;
var
cs: string;
cn: Connection;
cmd: Command;
p: _Parameter;
recordsAffected: OleVariant;
begin
cs := 'Provider=SQLOLEDB;Data Source=screwdriver;User ID=frog;Password=hunter2';
cn := CoConnection.Create;
WriteLn('Connecting to database...');
cn.Open(cs, '', '', Integer(adConnectUnspecified));
cmd := CoCommand.Create;
cmd.CommandType := adCmdText;
cmd.CommandText := 'IF ? IS NULL RAISERROR(''It was null'', 16, 1);';
cmd.Parameters.Append(cmd.CreateParameter('', adinteger, adParamInput, 0, 1));
cmd.Set_ActiveConnection(cn);
WriteLn('Executing command');
cmd.Execute({out}recordsAffected, Null, adExecuteNoRecords);
end;
begin
try
CoInitialize(nil);
Main;
WriteLn('Success');
except
on E: Exception do
begin
Writeln(E.ClassName, ': ', E.Message);
end;
end;
WriteLn('Press enter to close...');
ReadLn;
end.
奖金阅读
解决方案
你应该在你的陈述中使用EmptyParam
而不是(这是论点)。 Null
cmd.Execute
Parameters
cmd.Execute({out}recordsAffected, EmptyParam, adExecuteNoRecords);
请参阅:执行方法(ADO 命令)
EmptyParam
应该与可选的 ole 参数兼容。您也可以OleVariant(cmd).Execute
在您的示例中使用。
推荐阅读
- python-3.x - dnspython:在 pycharm 中找不到模块
- react-admin - 调整 react-admin 应用程序侧边栏大小的简单解决方案
- php - 使用 JOIN 查询生成器时 Codeigniter 中的内部 500 服务器错误
- keil - Cppcheck 与 Keil 的集成
- .net - 使用自定义 Application Insight(仪器密钥)设置 Azure Functions 很热门?
- javascript - 带有队列的 Discord.js 音乐机器人不起作用
- amazon-web-services - 将 EBS 卷附加到 EKS 集群节点
- linq - .NET Core 中 IQueryable 中的反射
- css - 更改离子日期时间值的颜色
- asp.net-core - 部署后 ASP.Net Core 3.1 应用程序丢失会话变量