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

independently 2012-11-17 09:49:40
小弟初学数据库,遇到问题,请教高手,如下所述:

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中的代码,可以正常获取到数据,各位大侠能告诉小弟是什么原因????
...全文
157 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
你可以用profile跟踪一下,然后看看调用第一个存储过程的时候,生成的语句是什么
找猫画虎 2012-11-18
  • 打赏
  • 举报
回复
叶子 2012-11-18
  • 打赏
  • 举报
回复
如果两个存储过程都是对的,那么问题应该是VC6.0中采用ODBC方式的时候有什么限制吧?

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧