5

通过返回结果集而不是表或视图的 mssql 存储过程向我提供了从数据库读取的访问权限。但我希望能够使用 ORM 读取数据。

我尝试DBIx::Class::ResultSource::View将过程调用(例如EXEC my_stored_proc ?)用作自定义查询,但这不起作用,因为它试图将过程调用转换为选择语句。

有人有其他建议吗?

4

2 回答 2

6

不,没有合理的方法可以在 DBIx::Class 的上下文中执行存储过程。

据我所知,最接近解决方法的是“使用 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 的任何好处来解决您的麻烦。

于 2012-05-08T20:59:14.523 回答
-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 ]
    }
  ) ];
于 2011-09-23T00:25:49.763 回答