I migrated my MySQL database to SQL Server 2019.
Working fine with MySQL :
**$now = Carbon::now()->format('Y-m-d 23:59:00');
->leftJoin('abonnements', function ($join) use ($now) {
$join->on('abonnements.client_id', '=', 'clients.id')
->whereRaw(DB::raw("NOT EXISTS (
SELECT 1 FROM abonnements a1
where a1.date_fin_tolerance >= \"{$now}\" and a1.date_debut <= \"{$now}\"
and a1.client_id = clients.id
AND a1.created_at > abonnements.created_at
)"**
SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name: '2022-12-20 23:59:00'. (SQL: select count(*) as aggregate from [customers] left join [subscriptions] on [subscriptions].[customer_id] = [customers].[id] and NOT EXISTS (\r\n SELECT 1 FROM subscriptions a1\r\n where a1.date_end_tolerance >= cast( "2022-12-20 23:59:00" as datetime) and a1.start_date <= cast("2022-12-20 23:59:00" as datetime)\r\n and a1.client_id = customers.id\r\n AND a1.created_at > subscriptions.created_at\r\n ) and [subscriptions].[end_tolerance_date] >= 2022-12-20 23:59:00 and [subscriptions].[start_date] < = 2022-12-20 23:59:00 left join [subscription_type] on [subscription_type].[subscription_type_id] = [subscription_type].[id] where [customers].[deleted_at] is null)"
Why it confuses the value with the column
Double quotes are used for an identifier (e.g.: column or table name) within SQL Server. Use single quotes to pass the datetime value as a string.
Related
I have an Oracle select that I need to execute in SQL Server (the table is exported from an Oracle database to a SQL Server database). I can replace nvl with isnull and decode with case I guess, but how to deal with the rowid in this specific case?
select sum(
nvl(
(select sum(b.restsaldo) from reskontro.erkrysskid b
where 1=1
and b.fakturanr = a.fakturanr
and b.kundenr = a.kundenr
and b.resknr = b.resknr
and a.rowid = decode(a.reskfunknr,31,a.rowid,b.rowid)
and nvl(b.restsaldo,0) <> 0
and b.krysskidid <= a.krysskidid
and not exists (select * from reskontro.erkrysskid c
where b.kundenr = c.kundenr
and b.resknr = c.resknr
and a.resklinr < c.resklinr
and a.krysskidid < c.krysskidid
and b.fakturanr = c.fakturanr
and c.reskfunknr in (31,75)
and nvl(c.attfort,-1) = -1)
),0
)
) as restsaldo from reskontro.erkrysskid a
where 1=1
and a.kundenr = 1
and a.resknr = 1
SQL Server doesn't have a ROWID pseudo column. In Oracle this is being used in the context of a self-join to determine if the two rows being joined are the same row. In SQL Server simply compare the table's key columns instead.
eg, if the table has a key on a Id column, use
and a.Id = case when a.reskfunknr = 31 then a.Id else b.Id end
I am trying to do a SELECT with UNION in Microsoft SQL Server where SQL statement has static string columns on which I would like to do a Group By. I am getting this error:
[Code: 207, SQL State: S0001] Invalid column name 'chrg_tx'. [Script position: 221 - 237]
The same SQL works in other RDBMS like INFORMIX.
Here is my SQL
SELECT
'' AS chrg_tx,
SUM(gross_after_discount) gross,
SUM(tax) tax,
SUM(net) net
FROM
invce_line_item
WHERE
ctry_cd = 'US'
AND lcl_btch_id = '2021-11-1214:49:20.838.EN'
AND invce_no = 'INV000001'
AND tax != 0
AND insr = 0
GROUP BY
chrg_tx
UNION
SELECT
'ASSURANCE' AS chrg_tx,
SUM(insr + insr_dsct) gross,
SUM(insr_tax) tax,
SUM(net_insr) net
FROM
invce_line_item
WHERE
ctry_cd = 'US'
AND lcl_btch_id = '2021-11-1214:49:20.838.EN'
AND invce_no = 'INV000001'
AND insr != 0
GROUP BY
chrg_tx
What can I try to resolve this?
My application uses a query that is working fine using a MySQL/MariaDB-Database.
I did modify my application to be more flexible and work with Microsoft SQL Server too.
Unfortunately the following query does NOT work using a SQL Server database:
select
p.PrinterGUID,
(exists (select 1
from computerdefaultprinter cdp
where cdp.PrinterGUID = p.PrinterGUID and
cdp.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f')
) as is_computer_default,
(exists (select 1
from userdefaultprinter udp
where udp.PrinterGUID = p.PrinterGUID and
udp.UserGUID = 'd3cf699b-8d71-4dbc-92f3-402950042054')
) as is_user_default
from
((select cm.PrinterGUID
from computermapping cm
where cm.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'
) union -- to remove duplicates
(select PrinterGUID
from usermapping um
where um.UserGUID = 'd3cf699b-8d71-4dbc-92f3-402950042054')) p;
Running this query throws an error
Incorrect syntax near the keyword 'exists'
Microsoft SQL Server Management Studio returns the following in German:
I have created a SQL Fiddle with some example data: SQL-Fiddle
If necessary, more background-information is available here: UNION 2 Select-queries with computed columns
Is it possible to modify this query to work in both MySQL and SQL Server?
Thank you very much!
The literal translation of your query would be the following:
select
p.PrinterGUID,
CASE WHEN exists (select 1
from computerdefaultprinter cdp
where cdp.PrinterGUID = p.PrinterGUID and
cdp.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f')
THEN 1 ELSE 0 END as is_computer_default,
CASE WHEN exists (select 1
from userdefaultprinter udp
where udp.PrinterGUID = p.PrinterGUID and
udp.UserGUID = 'd3cf699b-8d71-4dbc-92f3-402950042054')
THEN 1 ELSE 0 END as is_user_default
from (select cm.PrinterGUID
from computermapping cm
where cm.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'
union -- to remove duplicates
select PrinterGUID
from usermapping um
where um.UserGUID = 'd3cf699b-8d71-4dbc-92f3-402950042054') p;
Notice the use of a CASE expressions to determine the value of the column for when the EXISTS evaluates to true or not.
Just try out the following query. You don't need to use exists like this in sql server. Instead filter out the rows at the end using is_computer_default or is_user_default
select p.PrinterGUID,
(select 1
from computerdefaultprinter cdp
where cdp.PrinterGUID = p.PrinterGUID and
cdp.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f')
as is_computer_default,
(select 1
from userdefaultprinter udp
where udp.PrinterGUID = p.PrinterGUID AND
udp.UserGUID = 'd3cf699b-8d71-4dbc-92f3-402950042054'
) as is_user_default
from ((select cm.PrinterGUID
from computermapping cm
where cm.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'
) union -- to remove duplicates
(select PrinterGUID
from usermapping um
where um.UserGUID = 'd3cf699b-8d71-4dbc-92f3-402950042054'
)
) p;
I'm trying to create a temporary table in Microsoft SQL Server, then insert data into it, then return the data to Python as a dataframe, preferably.
Here is my connection, which works fine (password hidden).
EKA = turbodbc.connect(dsn='ekaprd', uid='smccarth', pwd='*****', database="Eka", turbodbc_options = turbodbc.make_options(prefer_unicode=True))
Here is the SQL string I want to run:
sql_string = """
create table #retaildeals
(
TransactionType varchar(10),
TCID int,
TID int,
ItemID int,
strategyID int,
Commodity varchar(10),
BuyOrSell varchar(10),
Category varchar(50)
)
insert into #retaildeals
select
'Physical',
ti.TransactingCompanyID,
ti.TransactionID,
ti.TransactionItemID,
th.strategyID,
tpd.Commodity,
tpd.BuyOrSell,
isnull(tci.categoryvalue, '')
from TransactionHeader TH (nolock)
inner join strategy S (nolock)
on s.StrategyID = th.StrategyID
inner join transactionitem TI (nolock)
on th.TransactingCompanyID = ti.TransactingCompanyID
and th.TransactionID = ti.TransactionID
inner join TransactionPhysicalDetail TPD (nolock)
on tpd.TransactingCompanyID = ti.TransactingCompanyID
and tpd.TransactionID = ti.TransactionID
and tpd.TransactionItemID = ti.TransactionItemID
inner join TransactionCategory TC (nolock)
on tc.TransactingCompanyID = th.TransactingCompanyID
and tc.TransactionID = th.TransactionID
left join TransactionCategoryItem TCI (nolock)
on tc.CategoryItemID1 = tci.CategoryItemID
where
th.IsVoid = 0
and ti.IsVoid = 0
and th.transactiontypeid in (50, 53)
group by
ti.TransactingCompanyID,
ti.TransactionID,
ti.TransactionItemID,
th.strategyID,
tpd.commodity,
tpd.BuyOrSell,
isnull(tci.categoryvalue, '')
"""
Finally, I try to execute the query string:
cursor = EKA.cursor()
cursor.execute(sql_string)
And I get the following error:
DatabaseError: ODBC error
state: 42S02
native error code: 208
message: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name '#retaildeals'.
The above SQL code works fine when I execute it in programs such as Aqua Data Studio, or as a passthrough query in SAS. Why doesn't it work when done in Python?
I had to use [enmax].[smccarth].[#retaildeals] instead of just #retaildeals.
I need to know if the used INTO SQL Server and equivalent ROWNUM in SQL Server
SELECT
SERIE, CORRELATIVO
INTO
vSerie, vCorrelativo
FROM
SIG.SAF_SERIES_DOCUMENTOS_DET
WHERE
COMPANIA = pCompania
AND MONTO = pMonto
AND ESTADO = 'P'
AND ROWNUM = 1;
This should do it, although you're missing an order by:
SELECT top 1
#vSerit = SERIE,
#vCorrelativo = CORRELATIVO
FROM SIG.SAF_SERIES_DOCUMENTOS_DET
WHERE COMPANIA = #pCompania
AND MONTO = #pMonto
AND ESTADO = 'P'
If you need something else than the first row, You can also do a row_number() window function as a column into your select and use that to limit the data or use offset / fetch if you're in SQL Server 2012 or use top twice with asc / desc order by