8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RubyからSQLServerのストアドを呼び出す

Last updated at Posted at 2015-04-07

##概要
Rubyを使用して簡単にSQLServerのストアドを呼び出す。
##やりたいこと
Rubyを使用してSQLServerのストアド(usp_read_m_user)を使用してユーザーマスタを参照する。

m_userのテーブル構造

UserID UserName
00000001 藤沼悟
00000002 雛月加代

##環境

  • Windows 8.1
  • Ruby 2.1.5p273
  • SQLServer 2008R2
  • activerecord-sqlserver-adapter (3.2.12)
  • tiny_tds (0.6.1 x86-mingw32)

1.ストアド

ストアドプロシージャー
CREATE PROCEDURE [dbo].[usp_read_m_user]
@UserId nvarchar(10)
AS
BEGIN
	SELECT * FROM m_user
	WHERE UserID = @UserID;
END

2.GemFile

GemFile
source "https://rubygems.org"

gem 'activerecord-sqlserver-adapter', '3.2.12'
gem 'tiny_tds', '0.6.1'

3.database.yml

database.yml
development:
  adapter:  "sqlserver"
  host:     "ホスト名(端末名,IPアドレス等)"
  username: "ユーザー名"
  password: "パスワード"
  database: "データベース名"

4.コントローラー

app.rb
# coding:utf-8
require 'activerecord-sqlserver-adapter'
require 'tiny_tds'

ActiveRecord::Base.configurations = YAML.load_file('database.yml')
ActiveRecord::Base.establish_connection(:development)
use ActiveRecord::ConnectionAdapters::ConnectionManagement

def readData
    rtns = ActiveRecord::Base.execute_procedure :usp_read_m_user, UserId: '00000002'
	rtns.each do |r|
		r.each{|key,value|
			puts key,value
		}
	end
end

####構文
ActiveRecord::Base.execute_procedure :ストアド名, パラメータ1, パラメータ2, パラメータ3
又は
ActiveRecord::Base.execute_procedure :ストアド名, named: パラメータ

5.実行結果

名称未設定-1.jpg

参考:activerecord-sqlserver-adapter

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?