简体   繁体   English

通过activerecord-sqlserver-adapter连接到SQL Server 2005时从Rails执行SQL查询

[英]Execute SQL query from Rails when connecting to SQL Server 2005 through activerecord-sqlserver-adapter

So I'm connecting to SQL Server 2005 from my Rails app via the activerecord-sqlserver-adapter. 因此,我要通过activerecord-sqlserver-adapter从我的Rails应用程序连接到SQL Server 2005。

I'm able to execute stored procs by doing 我可以通过执行存储的过程

Mymodel.execute_procedure("thisProcedure", param1, param2)

But I have a stored proc that has a SQL INOUT variable that I'm having trouble with. 但是我有一个存储过程,其中包含我遇到问题的SQL INOUT变量。 I execute it, and I'm not seeing that variable returned. 我执行它,但没有看到该变量返回。

So now I'm trying to just execute some raw sql, such as 所以现在我试图只执行一些原始sql,例如

declare @thisVar int
EXEC thatProcedure 1, 1, @thisVar = @thisVar output
print @thisVar

When I do 当我做

sql = "declare @thisVar int
EXEC thatProcedure 1, 1, @thisVar = @thisVar output
print @thisVar"

foo = Mymodel.connection.execute(sql)

I'm not getting any errors and everything looks successful. 我没有收到任何错误,一切看起来都很成功。 I get back foo that has a class of DBI::StatementHandle. 我回来了foo,它具有DBI :: StatementHandle类。 How do I actually see the response from the SQL? 我实际上如何查看来自SQL的响应?

Thanks in advance! 提前致谢!

It has been a while since I waded into DBI, we left stored procedures in favor of ORMs. 自从涉足DBI以来已经有一段时间了,我们离开了存储过程,转而支持ORM。 To get the data from the StatementHandle object, you need to issue a fetch all. 要从StatementHandle对象获取数据,您需要发出全部获取指令。 That should have all of your return values/output parameters as well as result set if applicable as an array. 那应该具有所有返回值/输出参数以及结果集(如果适用于数组)。 This was dbi version .4.1 which I believe is the last version to work with the sqlserver adapter. 这是dbi版本.4.1,我认为这是可与sqlserver适配器一起使用的最新版本。

sql = "declare @thisVar int
EXEC thatProcedure 1, 1, @thisVar = @thisVar output
print @thisVar"

foo = Mymodel.connection.execute(sql)

result_array = foo.fetch_all

and then you can loop through the resulting array. 然后您可以遍历结果数组。

Here is the DBI documentation http://ruby-dbi.rubyforge.org/rdoc/index.html 这是DBI文档http://ruby-dbi.rubyforge.org/rdoc/index.html

You might want to also look at the new activerecord-sqlserver-adapter. 您可能还需要查看新的activerecord-sqlserver-adapter。 It eliminates DBI entirely, not sure how it handles SPs though. 它完全消除了DBI,尽管不确定如何处理SP。

http://github.com/rails-sqlserver/2000-2005-adapter http://github.com/rails-sqlserver/2000-2005-adapter

My advice, for what it is worth, mixing ORMs and stored procedures is extremely difficult because you are splitting the business logic between two layers and it gets increasingly difficult to manage. 就其价值而言,我的建议是,将ORM与存储过程混合在一起非常困难,因为您将业务逻辑划分为两层,并且管理起来变得越来越困难。

Best of luck! 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM