How to convert this select from Oracle to SQL Server? - sql-server

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

Related

Replacement for rowid in SQL Server

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

Incorrect syntax near "Exists" … - Convert Query from MySQL to SQL Server

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;

Emulate sql Server ROW_COUNT() for SQL Server Version 8.00.760

I need to make a query with the ROW_NUMBER() function in order to enumerate all purchase order Lines order by the PurchaseID and date of delivery:
SELECT
PL.PURCHID,
PL.LINENUMBER,
ROW_NUMBER() OVER (PARTITION BY PL.PURCHID
ORDER BY PL.LineNumber, PL.DELIVERYDATE DESC) AS LineNumberOrdered
FROM AXDB13_R1.dbo.PURCHLINE PL
WHERE PL.DATAAREAID = 'pol';
the thing is that the database production is too old that does not recognize that function. How can I emulate that?
thanks a lot for your help!
We can replace your call to ROW_NUMBER with a correlated count query, which generates counts over what previously was each partition of PURCHID:
SELECT
PL.PURCHID,
PL.LINENUMBER,
(SELECT COUNT(*)
FROM AXDB13_R1.dbo.PURCHLINE PL2
WHERE PL2.PURCHID = PL.PURCHID AND
(PL2.LineNumber < PL.LineNumber OR
PL2.LineNumber = PL.LineNumber AND
PL2.DELIVERYDATE >= PL.DELIVERYDATE)) AS LineNumberOrdered
FROM AXDB13_R1.dbo.PURCHLINE PL
WHERE
PL.DATAAREAID = 'pol';

Converting Entity Framework query with join and group by to SQL Server query

I having problems converting linq query to a SQL Server query.
var gdevices = (from logs in dbContext.GensetLogs
group logs by logs.DeviceId into logsgroup
join devices in dbContext.GensetDevices on logsgroup.FirstOrDefault().DeviceId equals devices.Id
where devices.RegisteredBy == model.Email || devices.OperatedBy == model.Email || model.StType == "admin"
select new DeviceRegistrationDTO
{
PhoneNumber = devices.PhoneNumber,
Latitude = devices.Latitude,
Longitude = devices.Longitude,
LatestRT = logsgroup.Max(d => d.ReadingTime),
DeviceName = logsgroup.Max(d => d.ReadingTime).DeviceName,
OperatedBy = devices.OperatedBy,
ThresholdValue = devices.ThresholdValue
}).ToList();
If you are trying to convert from Linq to sql queries then use as following
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
Ref:
https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx
i done this in very simple way.
SELECT (t.[TransId])
, t.[SGCode]
, t.PurchaseDate
, t.SoldTo
,t.Cost
,(select top 1 dr.Rate from DepreciationRate dr where t.Assets_TransId = dr.Assets_TransId order by dr.DepDate desc) Rate
,(select sc.Name from AssetsSubClass sc where t.SubClass_TransId = sc.TransId) Name
FROM AssetsTransctions t

SQL Query conversion from sybase to SQL Server

select a.dda_pk
from direct_table a
where a.dda_type = 'B'
and a.dda_status = 'D'
and a.dda_location = '01'
group by a.dda_emp_idno
having dda_pk < max(a.dda_pk)
and a.dda_status = 'D'
and a.dda_location = '01'
Column 'direct_deposit_audit.dda_pk' is invalid in the HAVING clause
because it is not contained in either an aggregate function or the
GROUP BY clause.
This is based on a assumption that the SQL returns rows for each dda_emp_idno
where dda_pk is smaller than the maximum dda_pk for that dda_emp_idno.
This should do the same thing in SQL Server:
select dda_pk
from (
select
dda_pk,
dense_rank() over (partition by dda_emp_idno order by dda_pk desc) as RN
from
direct_table a
where
a.dda_type = 'B'
and a.dda_status = 'D'
and a.dda_location = '01'
) X
where RN > 1
All the elements in group by must be in select clause so you can try this:
select a.dda_pk
from direct_table a
where a.dda_type = 'B'
and a.dda_status = 'D'
and a.dda_location = '01'
group by a.dda_pk
having a.dda_pk < max(a.dda_pk)
and a.dda_status = 'D'
and a.dda_location = '01'
Without having dug into this query, let me just note that Sybase ASE has much looser semantics around the GROUP BY than most other databases. This means that queries with GROUP BY that run iN ASE may raise an error in other databases.
For more info, see http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.help.ase.15.7/title.htm

Resources