Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement SQL Server Utilities Statements - GO #72

Closed
comsma opened this issue Nov 30, 2022 · 3 comments
Closed

implement SQL Server Utilities Statements - GO #72

comsma opened this issue Nov 30, 2022 · 3 comments

Comments

@comsma
Copy link

comsma commented Nov 30, 2022

I would like to be able to use the GO statement within my sql statement so I can run batches.

@shueybubbles
Copy link
Collaborator

We have a sqlcmd script execution package at https://github.com/microsoft/go-sqlcmd/pkg/sqlcmd that might be appropriate. If you provide the sqlcmd instance with your own implementation of Formatter you'll get access to the driver data.

@comsma
Copy link
Author

comsma commented Nov 30, 2022

would I replace the go-mssql import? This is how i'm currently using the package

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/microsoft/go-mssqldb"
	"math"
	"os"
)

var db *sql.DB

func main() {

	files, _ := os.ReadDir(".")

	openDb("sqlserver://xxx")

	batches := len(files) / 500
	batches = int(math.Round(float64(batches)))
	fmt.Println(batches)

	for batch := 0; batch < batches; batch++ {
		sendScriptsAsQuery(files[(batch*500)+0 : (batch*500)+500])
	}

	sendScriptsAsQuery(files[2000:2500])
	defer db.Close()

}

func openDb(connectionUrl string) {
	var err error
	db, err = sql.Open("mssql", connectionUrl)
	if err != nil {
		fmt.Println("Cannot connect: ", err.Error())
		return
	}
	err = db.Ping()
	if err != nil {
		fmt.Println("Cannot connect: ", err.Error())
		return
	}
}

func sendScriptsAsQuery(scripts []os.DirEntry) {

	for s := 0; s < len(scripts); s++ {
		data, _ := os.ReadFile(scripts[s].Name())

		_, errs := db.Exec(string(data[:]))
		if errs != nil {
			fmt.Printf("%s \n", errs)
		}
	}

}

@shueybubbles
Copy link
Collaborator

if you are trying to run the scripts without examining the output, you could just run sqlcmd in the shell instead of writing your own app to do it. We have releases for most platforms.
Otherwise you would use import the github.com/microsoft/go-sqlcmd/pkg/sqlcmd package and use the IncludeFile method.

Like this test: https://github.com/microsoft/go-sqlcmd/blob/9b59da694f9cbdf87acf70589e4c680589917f1a/pkg/sqlcmd/sqlcmd_test.go#L145

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants