laura
laura

Reputation: 2135

How to call SQL function from Qt

I have a function which returns an integer. I can't figure how to call this function in Qt.

create function isLastAppVersion(
     @currentVersion nvarchar(10),
     @appCode nvarchar(128),
     @serial nvarchar(128))
returns int
as 
begin
    declare @ret int
    select @ret = case 
    when @currentVersion = (select *from getAppLastVersion(@appCode,@serial)) 
    then 1 else 0 end
    return @ret
end

From Sql server i call it like this:

declare @i int
exec @i = dbo.isLastAppVersion @currentVersion = '2.1',@appCode = '33fdd5f4-e24b-11e3-a375-82687f4fc15c',@serial='14jt-cf3c-24b1-c1e3'
print @i

How to do this from Qt? This is what i tried. But it is not working

QString DBConnection::isLastVersion(QString version, QString appCode, QString serialNo){
    QSqlQuery query;
    QString result;


    QString connectionString = connection.arg(serverName).arg(dbName);
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");

    db.setDatabaseName(connectionString);

    if (db.open())
    {
        qDebug() << "Opened";
        query = db.exec("isLastAppVersion('" + version + "','" + appCode + "','" + serialNo + "');");

        while(query.next()){
            result = query.record().value(0).toString();
            qDebug() << "Result la functie is last version: " << result;
        }
        db.close();
    }
    else
    {
        qDebug() << "Error = " << db.lastError().text();
    }
    db.close();

    return result;
}

Upvotes: 0

Views: 1240

Answers (1)

M.Ali
M.Ali

Reputation: 69554

Since it is a Function it will be called via SELECT statement, Like you would call any sql server's built-in functions (GETDATE(), SUM(), COUNT())

In your case it would be something like....

SELECT dbo.isLastAppVersion('2.1'
                            ,'33fdd5f4-e24b-11e3-a375-82687f4fc15c'
                            ,'14jt-cf3c-24b1-c1e3')

Or if you want to store the returned value to a variable simply do this...

declare @i int;
SELECT @i = dbo.isLastAppVersion('2.1'
                                ,'33fdd5f4-e24b-11e3-a375-82687f4fc15c'
                                ,'14jt-cf3c-24b1-c1e3')

PRINT @i    

Note

Also in your function definition you have the following line

when @currentVersion = (select *from getAppLastVersion(@appCode,@serial))

I believe getAppLastVersion is another Table-Values Functions. If this function is returning Multiple columns back, then you need to select one Only One column from this select statement. Also if there is a chance that this function can return multiple rows back make sure you also use TOP 1 clause in your Select statement, As you are comparing the results returned by this function with a scalar value.

So you need to make sure that this function returns Single value when its called and you are comparing a single value with your @currentVersion variable.

Upvotes: 1

Related Questions