2011-09-22 20 views
5

從數據庫讀取的訪問權限已通過返回結果集而不是表或視圖的mssql存儲過程提供給我。但我希望能夠使用ORM讀取數據。可以將DBIx :: Class與存儲過程(而不是表)一起使用嗎?

我試圖用DBIx::Class::ResultSource::View做的程序呼叫(例如EXEC my_stored_proc ?)作爲一個自定義查詢,但並沒有工作,因爲它試圖把過程調用轉換爲select語句。

有沒有人有另一個建議?

回答

5

沒有,有在DBIx ::類的上下文中執行存儲過程沒有合理的方式。

據我所知道的,最接近一個解決辦法是「使用ORM」來獲得一個數據庫句柄,這是弱湯:

my @results = $schema->storage->dbh_do(sub{ 
     my ($storage, $dbh, @args) = @_; 
     my $sth = $dbh->prepare('call storedProcNameFooBar()'); 
     my @data; 
     $sth->execute(); 
     while(my $row = $sth->fetchrow_hashref){ 
      push @data, $row; 
     } 
     return @data; 
    },()); 

[在 http://metacpan.org/pod/DBIx::Class::Storage::DBI#dbh_do查看詳細信息]

...因爲你沒有得到一個ORM的好處,因爲你的麻煩。

+0

'DBIx :: Class :: Manual :: Cookbook' docs節'使用數據庫函數或存儲過程',儘管@stevenl指出它不會幫助MS SQL Server,因爲它顯然無法訪問存儲過程通過SELECT語句。 – LeeGee

+1

也不是Mysql,我的猜測也不是Oracle。我想知道DBIx:Class手冊的作者是否只是補充它。 – djsadinoff

+0

確實 - 預期的行爲是什麼? DBIC如何知道使用哪個ResultSet關聯存儲過程或函數返回的數據?我認爲作者的意思是'函數',就像在SQL函數中一樣,'length'就是例子。這並不能解釋如何添加「存儲過程」。 – LeeGee

-2

您可以使用register_source

package My::Schema::User; 

    use base qw/DBIx::Class/; 

    # ->load_components, ->table, ->add_columns, etc. 

    # Make a new ResultSource based on the User class 
    my $source = __PACKAGE__->result_source_instance(); 
    my $new_source = $source->new($source); 
    $new_source->source_name('UserFriendsComplex'); 

    # Hand in your query as a scalar reference 
    # It will be added as a sub-select after FROM, 
    # so pay attention to the surrounding brackets! 
    $new_source->name(\<<SQL); 
    (SELECT u.* FROM user u 
    INNER JOIN user_friends f ON u.id = f.user_id 
    WHERE f.friend_user_id = ? 
    UNION 
    SELECT u.* FROM user u 
    INNER JOIN user_friends f ON u.id = f.friend_user_id 
    WHERE f.user_id = ?) 
    SQL 

    # Finally, register your new ResultSource with your Schema 
    My::Schema->register_source('UserFriendsComplex' => $new_source); 

要使用參數呼叫執行以下

my $friends = [ $schema->resultset('UserFriendsComplex')->search({ 
+}, 
    { 
     bind => [ 12345, 12345 ] 
    } 
) ]; 
+0

該解決方案看起來與我使用ResultSource :: View非常相似。這種方法的問題是它將我的存儲過程調用添加爲子選擇的部分。生成的查詢將如下所示:'SELECT me.x FROM(EXEC my_stored_proc?)me',這會導致語法錯誤,並且無法準備語句。我猜這個問題不會特定於mssql,因爲我沒有看到其他平臺具有兼容的語法。 – stevenl

+1

這並不回答這個問題。這裏沒有存儲過程。 – djsadinoff

相關問題