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

QueryRow doesn't work as documented #126

Closed
mikewilliamson opened this issue Sep 11, 2015 · 3 comments
Closed

QueryRow doesn't work as documented #126

mikewilliamson opened this issue Sep 11, 2015 · 3 comments

Comments

@mikewilliamson
Copy link

I'm using this fragment of code, which is taken almost verbatim from the example given in the QueryRow documentation:

var Id int
err = db.QueryRow("select max(EventId) from Event").Scan(&Id)
switch {
case err == sql.ErrNoRows:
    log.Printf("No EventId.")
case err != nil:
    log.Fatal(err)
default:
    fmt.Printf("Max EventId is %v\n", Id
}

According to the docs, you would expect the message No EventId, but what you get is this:

2015/09/11 10:38:53 sql: Scan error on column index 0: converting string "<nil>" to a int: strconv.ParseInt: parsing "<nil>": invalid syntax

Is this a bug in the driver, or in the sql package?

@dimdin
Copy link
Collaborator

dimdin commented Sep 11, 2015

@mikewilliamson what is the database type of Event.EventId ?

@dimdin
Copy link
Collaborator

dimdin commented Sep 11, 2015

@mikewilliamson I can reproduce it with the code:

func TestBug126(t *testing.T) {
    conn := open(t)
    defer conn.Close()
    var Id int
    err := conn.QueryRow("select null").Scan(&Id)
    if err != nil {
        t.Fatal("Cannot scan to int: ", err.Error())
    }
}

select max(EventId) from Event is going to return null when there are no records in Event.
You can not scan a null value to int, so this is not a bug.
To solve your problem try this query:

select max(EventId) from Event where exists (select 1 from Event)

@mikewilliamson
Copy link
Author

Ah, got it, thanks. I was mistakenly thinking that the query would return no rows rather than one row with a null. My mistake. Actually what I want is something like:

select isnull(max(EventId), 0) from Event

odeke-em pushed a commit to orijtech/go-mssqldb that referenced this issue Jul 26, 2020
Include details about migration locking in the FAQ
gabrielcorado pushed a commit to gravitational/go-mssqldb that referenced this issue Oct 4, 2024
…er (denisenkom#126)

* Added MarshalText() and UnmarshalJSON interfaces

- The existing MarshalText() for the UniqueIdentifier type had a bad signature. It omitted returning an error that the interface expects.
- Added UnmarshalJSON() interface to the UniqueIdentifier type with a test as well

* use strings.Replace instead of ReplaceAll
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