双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

急!急!急!VC调用含动态输入条件的存储过程出现问题!

independently independently 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
小弟初学数据库,遇到问题,请教高手,如下所述:

1、SQL Server2005存储过程,该存储过程编译通过,测试功能正常:
if exists(select * from sys.objects where object_id = OBJECT_ID('dbo.p_QueryCity') and type = 'P')
drop procedure dbo.p_QueryCity;
go
Create Procedure dbo.p_QueryCity
@CityName nvarchar(50)
as
declare @Ret int,@Reason nvarchar(max);
select @Ret = 0,@Reason = N'';
declare @sqlcmd nvarchar(max)
,@CityNameCondition nvarchar(max)

select @sqlcmd = 'select
CityName
,CityNameDesp
,CityLoc
from CityTable where 1 = 1';

--动态条件查询
if @CityName <>'' and @CityName is not null
select @CityNameCondition = ' and CityName = '''+@CityName+'''';
else
select @CityNameCondition = '';

select @sqlcmd = @sqlcmd+@CityNameCondition

print @sqlcmd;
exec sp_executesql @sqlcmd

if @@error <> 0
begin
select @Ret = -1, @Reason = N'T-SQL DML命令执行时错误';
end

select @Ret as ret, @Reason as failreason;
return @Ret;
go

2、VC6.0代码中与数据库SQL Server2005采用ODBC方式,
调用存储过程代码如下:
前面连接数据库就省略不写了,直接写如何调用存储过程:
//.....连接数据库过程省略

SQLRETURN hRecode;
SQLINTEGER CbSatid = SQL_NTS;
//执行SQL命令
hRecode = SQLExecDirect(m_hstmt, (UCHAR*)"exec p_QueryCity ''", SQL_NTS);
if ( (hRecode != SQL_SUCCESS) && (hRecode != SQL_SUCCESS_WITH_INFO) )
{
return;
}
//获取结果集
while ( hRecode = SQLFetch(m_hstmt ) != SQL_NO_DATA_FOUND)
{
//此时已经有问题了,下面的SQLGetData也不会取到任何数据,
//此时调用SQLError函数获取到SqlState = 24000,ErrorMsg = [Microsoft][ODBC SQL Server Driver]无效的游标状态

char szCity[100] = {0};
char CityNameDesp[100] = {0};
char CityLoc[100] = {0};

SQLGetData(m_hstmt, 1, SQL_C_TCHAR, szCity, 99, &CbSatid);
SQLGetData(m_hstmt, 2, SQL_C_TCHAR, CityNameDesp, 99, &CbSatid);
SQLGetData(m_hstmt, 3, SQL_C_TCHAR, CityLoc, 99, &CbSatid);

}

3、后来对数据库存储过程修改为如下:
if exists(select * from sys.objects where object_id = OBJECT_ID('dbo.p_QueryCity') and type = 'P')
drop procedure dbo.p_QueryCity;
go
Create Procedure dbo.p_QueryCity
@CityName nvarchar(50)
as
declare @Ret int,@Reason nvarchar(max);
select @Ret = 0,@Reason = N'';

select
CityName
,CityNameDesp
,CityLoc
from CityTable where 1 = 1 and (@CityName is null or @CityName = '' or CityName = @CityName);


if @@error <> 0
begin
select @Ret = -1, @Reason = N'T-SQL DML命令执行时错误';
end

select @Ret as ret, @Reason as failreason;
return @Ret;
go

4、重新执行步骤2中的代码,可以正常获取到数据,各位大侠能告诉小弟是什么原因????
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
independently
MS-SQL Server 34,876 成员 254,635 内容