Skip to content

MSSQL translator should convert as.logical into CAST AS BIT instead of CAST AS BOOLEAN #250

@jcfisher

Description

@jcfisher

In MS SQL Server, as.logical translates to CAST AS BOOLEAN. However, in SQL Server, it looks like BOOLEAN doesn't exist. It seems to use BIT instead of BOOLEAN.

It seems like this might be a simple fix. A small example follows. Let me know if there's anything I can do to help fix, if this is of interest.

library(tidyverse)
library(dbplyr)
con <- DBI::dbConnect(
  odbc::odbc(),
  driver = "{SQL Server}",
  database = "AdventureWorks2012",
  uid = "sqlfamily",
  pwd = "sqlf@m1ly",
  server = "mhknbn2kdz.database.windows.net",
  port = 1433
)

# Fails
con %>% 
  tbl(in_schema("Production", "WorkOrder")) %>% 
  transmute(large_order = as.logical(if_else(OrderQty < 5, 0L, 1L)))
# Error: <SQL> 'SELECT  TOP 10 "large_order" AS "large_order"
# FROM (SELECT "WorkOrderID", "ProductID", "OrderQty", "StockedQty", "ScrappedQty", "StartDate", "EndDate", "DueDate", "ScrapReasonID", "ModifiedDate", CAST(CASE WHEN ("OrderQty" < 5.0) THEN (0) # ELSE (1) END AS BOOLEAN) AS "large_order"
# FROM Production.WorkOrder) "zvtstdmghk"'
#   nanodbc/nanodbc.cpp:1587: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Type BOOLEAN is not a defined system type. 

# Works
con %>% 
  tbl(sql('SELECT CAST(CASE WHEN ("OrderQty" < 5.0) THEN (0) ELSE (1) END AS BIT) AS "large_order"
           FROM Production.WorkOrder'))
# # Source:   SQL [?? x 1]
# # Database: Microsoft SQL Server 12.00.1100[sqlfamily@mhknbn2kdz/AdventureWorks2012]
#    large_order
#          <lgl>
#  1        TRUE
#  2        TRUE
#  3        TRUE
#  4        TRUE
#  5        TRUE
#  6        TRUE
#  7       FALSE
#  8        TRUE
#  9       FALSE
# 10       FALSE
# # ... with more rows

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorfunc trans 🌍Translation of individual functions to SQL

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions