Server SQL中的存儲過程如下:
CREATE procedure PINSERTPC
@pcnum int,
@pcname varchar(50),
@pctype int,
@ipaddress varchar(50),
@port int,
@pcid int output
as--declare @pcid int
if exists (select * from COMPUTERTABLE where PcNum = @pcnum)
set @pcid = -1
else
begin
insert into COMPUTERTABLE (PcNum, PcName, PcType, IpAddress, Port)
values (@pcnum, @pcname, @pctype, @ipaddress, @port)
select @pcid = SCOPE_IDENTITY()
end
--return @pcid
GO
根據網上搜索文章《qt中調用sql server的存儲過程》內容如下:
寫了個存儲過程,准備使用qt調用,數據庫是sqlserver 2000按照參考文檔
調用是下面這樣的
QSqlQuery query;
query.prepare("CALL InsertImgEntity( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
query.bindValue(0,datano);
query.bindValue(1,DataCorner);
query.bindValue(2,DataZD);
query.bindValue(3,DataCommon);
query.bindValue(4,ImgCode);
query.bindValue(5,ImgCodeZ);
query.bindValue(6,"png");
query.bindValue(7,pngImage,QSql::Binary);
query.bindValue(8,"GoldMap Gaoyong Sun");
query.bindValue(9,QDateTime::currentDateTime ());
但是我在windows下卻無法調用成功。調試跟蹤,發覺我在調試中存儲過程是通過exec調用的,故此將代碼修改如下,問題解決,造成這種結果的原因可能是數據庫的不同吧。
query.prepare("exec InsertImgEntity ?, ?, ?, ?, ?, ?, ?, ?, ?, ?");
query.bindValue(0,datano);
query.bindValue(1,DataCorner);
query.bindValue(2,DataZD);
query.bindValue(3,DataCommon);
query.bindValue(4,ImgCode);
query.bindValue(5,ImgCodeZ);
query.bindValue(6,"png");
query.bindValue(7,pngImage,QSql::Binary);
query.bindValue(8,"GoldMap Gaoyong Sun");
query.bindValue(9,QDateTime::currentDateTime ());
可是工作需要,存儲過程中要有返回值,或者輸出參數,返回當前插入的ID號。通過測試得到解決方法。以最上方存儲過程為例Qt中代碼如下:
bool QtSqlServer::SqlInsertPcData(QtPcData* pcData)
{
bool bFlag = false;
QSqlQuery query;
query.prepare("exec PINSERTPC ?, ?, ?, ?, ?, ? output");
query.bindValue(0, pcData->GetPcNum());
query.bindValue(1, pcData->GetPcName());
query.bindValue(2, pcData->GetPcType());
query.bindValue(3, pcData->GetIpAddress());
query.bindValue(4, pcData->GetPort());
query.bindValue(5, 0, QSql::Out);
bFlag = query.exec();
if (bFlag)
{
int pcID = query.boundValue(5).toInt();
if (pcID < 0)
{
bFlag = false;
}
else
{
pcData->SetPcID(pcID);
bFlag = true;
}
}
else
{
QString str = query.lastError().text();
QMessageBox::critical(0, QObject::tr("Error"),QObject::tr("%1").arg(str));
}return bFlag;
}
也存在一些未知的疑問……這里的輸出參數必須設置在存儲過程的最后一個參數中返回,而且根據Server SQL中的要求必須有output的修飾,這樣才可確保成功。
疑問1:如果存儲過程想以返回值的形式返回,使用Qt如何調用。
疑問2:為何存儲過程的輸出參數必須設置才最后一個參數才可獲取到正確的輸出值,譬如想在第一個參數中返回,如何解決。
疑問3:有些存儲過程有多個輸出參數,但本人測試Qt只能以一個輸出參數形式(設置為最后一個參數)調用……這事讓我着實頭疼!整的我其他的輸出參數是在執着SQL語句查出來……
最近貌似挺貪玩....要收斂收斂了!嘿嘿!上述問題如果有人可以解答,小的十分感激,彼此交流,相互學習!
http://cool.worm.blog.163.com/blog/static/6433900620091018103220702/