最近遇到要写存储过程需求,使用 大佬写的 框架 gorm 来完成。简直是方便的不行:
直接上代码:
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlserver
代码:
/*
@Time : 2021/6/16 8:08
@Author : dao
@File : project
@Software: GoLand
*/
package main
import (
"fmt"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)
type Student struct {
Id int
Name string
baibai string
}
func (Student) TableName() string {
return "Student"
}
func main() {
fmt.Println("gorm 执行 存储过程 :")
dsn := "sqlserver://cuyan:123456@120.79.19.125:1433?database=cuyan"
db, _ := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
var students []Student
// 原生 SQL 查询
rows, _ := db.Raw("EXEC [dbo].[Go123] @name = N'z'").Rows()
defer rows.Close()
for rows.Next() {
db.ScanRows(rows, &students)
// 可写其他业务逻辑...
}
// 循环输出
for _, v := range students {
fmt.Println(v.Name)
}
}
附
存储过程图片
存储过程代码(创建)
CREATE PROCEDURE [Go1234]
(@name nvarchar )
-- Add the parameters for the stored procedure here
AS
BEGIN
SELECT [Id]
,[Name]
,[Gender]
,[IsGraduate]
FROM [cuyan].[dbo].[Student] where Name like '%'+@name+'%'
END
表结构
表结构图
表结构代码
USE [cuyan]
GO
/****** Object: Table [dbo].[Student] Script Date: 2021/6/16 8:34:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Gender] [int] NULL,
[IsGraduate] [bit] NULL,
CONSTRAINT [PK_Student_1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)