I'm working with SQL Server 2005, I'm new to SQL so bear with me.
The following aliased SQL query is giving me the following error:
The multi-part identifier "EquipmentDescription.DESCRIPTION" could not be bound.
SQL:
WITH somerows as
(
SELECT
Mastertable.ID, Mastertable.foo1, Mastertable.foo2,
Mastertable.foo3, EquipmentDescription.DESCRIPTION,
ROW_NUMBER() OVER (ORDER BY Mastertable.ID) AS SeqValue
FROM
EquipmentDescription
LEFT JOIN
MasterTable ON EquipmentDescription.foo1 = MasterTable.foo1
ORDER BY
EquipmentDescription.DESCRIPTION
)
SELECT *
FROM somerows
WHERE SeqValue BETWEEN 0 and 20
Background: Mastertable has 60,000+ records. I'm using WITH...as...etc to request 20 records at a time on the server side.
The DESCRIPTION column of EquipmentDescription for the purposes of design is not included in Mastertable. It is a requirement to include DESCRIPTION in the final select.
Any ideas on what I'm doing wrong?
This works:
SELECT * FROM
(
SELECT
ROW_NUMBER() OVER(ORDER BY ID) AS NUMBER,
Mastertable.ID, Mastertable.foo1, Mastertable.foo2,
Mastertable.foo3, EquipmentDescription.DESCRIPTION,
FROM
EquipmentDescription
RIGHT JOIN
MasterTable ON EquipmentDescription.foo1 = MasterTable.foo1
) AS t_MasterTable
WHERE
NUMBER BETWEEN 0 and 20
ORDER BY ID
Related
I am trying to convert the below MSSQL query into DB2 query.
But i am facing issues . I got to know "CROSS APPLY" doesnt exist for DB2
SQL Server query:
SELECT DISTINCT p.ID,
p.COMPANY,
p.NAME,
format(d.startTime, 'yyyy-MM-dd HH:mm:ss.fff')
FROM PROCESS p
CROSS APPLY (SELECT MAX(END_TIME) AS startTime FROM PROCESS WHERE ID = (SELECT MAX(ID) FROM PROCESS)) AS d
WHERE p.ID = (SELECT MAX(ID) FROM PROCESS)
Error:
Error: com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -104, SQLSTATE: 42601, SQLERRMC: APPLY;N process
CROSS;JOIN
How the above query can be converted into DB2 query format?
The SQL Server manual says that a CROSS APPLY is used with table functions.
https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-ver15#using-apply
That the right_table_source can use a table-valued function that takes a column from the left_table_source as one of the arguments of the function.
Your example does not use any, so I assume it is simply the equivalent to a CROSS JOIN in Db2.
By the way, this statement would likely get the same result (assuming COMPANY and NAME are the same for a given ID)
SELECT
ID
, COMPANY
, NAME
, format(END_TIME, 'yyyy-MM-dd HH:mm:ss.fff')
FROM
( SELECT *
, ROW_NUMBER() OVER(ORDER BY ID DESC, END_TIME DESC) AS RN
FROM
PROCESS p
)
WHERE
RN = 1
This might or might not be more optimal at execution time
The DB2 equivalent is the terribly named TABLE operator. The name makes it very challenging to find documentation.
See if this works for your query.
SELECT DISTINCT p.ID,
p.COMPANY,
p.NAME
FROM PROCESS p
JOIN TABLE (
SELECT ID
,MAX(END_TIME) AS startTime
FROM PROCESS
WHERE ID = (
SELECT MAX(ID)
FROM PROCESS
)
GROUP BY ID
) AS D
ON P.ID = D.ID
However, I've found CTEs in DB2 to be very effective. In SQL Server, a CTE is almost like a layer applied to a query, similar to a view. The expressions in the CTE are generally combined with the underlying statements and executed as a single statement.
I'm not a DB2 expert, but it seems to me that a CTE is materialized to an internal table and the result is combined with the remaining statements.
With the same query, data and indexes, DB2 and SQL Server can have very different performance when CTEs are involved.
I am trying to create a view in MS SQL server from a table. The table name is Account_Plan and I am trying to create a view as Account_Plan_vw. While executing the DDL to create the view, I am getting the error as shown below.
Msg 258, Level 15, State 1, Procedure Account_Plan_vw, Line 56
Cannot call methods on ntext
Msg 207, Level 16, State 1, Procedure Account_Plan_vw, Line 22
Invalid column name 'How_the_CU_will_achieve_these_objective2__c'.
The error message shows the column 'How_the_CU_will_achieve_these_objective2__c' as invalid. However, this is a valid column in the Account_Plan table of ntext type.
Can someone help? I just removed the extra columns from the Create view statement.
CREATE VIEW [dbo].[Account_Plan_vw]
AS
SELECT
Results_1.Account__c
,Results_1.How_the_CU_will_achieve_these_objectives__c
,Results_1.How_the_CU_will_achieve_these_objective2__c
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY apc1.Account__c ORDER BY apc1.Year__c DESC, apc1.CreatedDate DESC) AS RN_1
,apc1.Account__c
,apc1.How_the_CU_will_achieve_these_objectives__c
,apc1.How_the_CU_will_achieve_these_objective2__c
FROM Account_Plan apc1
INNER JOIN RecordType rtp1
ON apc1.RecordTypeId=rtp1.[Id]
AND rtp1.DeveloperName = 'Account_Plan'
INNER JOIN Account acc1
ON acc1.[Id] = apc1.Account__c
WHERE apc1.Year__c <= YEAR(GETDATE())
) AS Results_1
WHERE RN_1 = 1
NTEXT is deprecated, convert it to NVARCHAR(MAX) instead
see: ntext, text, and image (Transact-SQL)
You should consider altering the table not just casting in the view, but:
CREATE VIEW [dbo].[Account_Plan_vw]
AS
SELECT
results_1.Account__c
, results_1.How_the_CU_will_achieve_these_objectives__c
, results_1.How_the_CU_will_achieve_these_objective2__c
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY apc1.Account__c ORDER BY apc1.Year__c DESC, apc1.CreatedDate DESC) AS rn_1
, apc1.Account__c
, apc1.How_the_CU_will_achieve_these_objectives__c
, cast(apc1.How_the_CU_will_achieve_these_objective2__c as nvarchar(max)) as How_the_CU_will_achieve_these_objective2__c
FROM Account_Plan apc1
INNER JOIN RecordType rtp1 ON apc1.RecordTypeId = rtp1.[Id]
AND rtp1.DeveloperName = 'Account_Plan'
INNER JOIN Account acc1 ON acc1.[Id] = apc1.Account__c
WHERE apc1.Year__c <= YEAR(GETDATE())
) AS results_1
WHERE RN_1 = 1
the issue and it was somewhat cryptic to find. The salesforce object had a field as last_peer_review_date__c for which no permissions were given to anybody. As a result, DBAMP user was not able to see the field and hence missed to create this field in SQL server when I used the SF_Replicate command. The create view SQL was created by me couple of weeks ago and it did work at that time. Now, when I used the same SQL, it failed because the SQL had the last_peer_review_date field, but the Account_Plan table does not.
Balaji Pooruli
In my table I have the columns id, userId and points. As a result of my query I would like to have the id of the record that contains the highest points, per user.
In my experience (more with MySQL than SQL Server) I would use the following query to get this result:
SELECT id, userId, max(points)
FROM table
GROUP BY userId
But SQL Server does not allow this, because all columns in the select should also be in the GROUP BY or be an aggregate function.
This is a hypothetical situation. My actual situation is a lot more complicated!
Use ROW_NUMBER window function in SQL Server
Select * from
(
select Row_Number() over(partition by userId Order by points desc) Rn,*
From yourtable
) A
Where Rn = 1
I want a Sql Script Trigger on after insert, Which can Delete all Rows in table except Last Two Rows.
And I Want Similar Code in Entity linq too Please...
I know my question is cheap for you experts but i really do not know how to code it...
So help me please?
I Use This Code But Has error in syntax :
select * from TblGold where id not in (
select id from TblGold
order by id desc
limit 2
)
The Error Is :
Msg 102, Level 15, State 1, Line 4 Incorrect syntax near 'limit'.
By the way, I know how to write a trigger but do not know how to Delete All Records Except 2 Last record.
And nither Linq Codes.
WITH cte
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY Id DESC) AS RowNumber, *
FROM TblGold
)
DELETE TblGold
FROM
TblGold T
INNER JOIN cte ON cte.Id = T.Id
WHERE RowNumber > 2
I've been trying to replicate the limit and range feature provided in MySql in SQL Server with no luck as of yet. I have found several guides and now think my sql code is nearly correct but I'm still getting an error posted below.
System.Data.SqlClient.SqlException:
Only one expression can be specified
in the select list when the subquery
is not introduced with EXISTS
The error code says to use EXISTS but i have tried that instead of NOT IN and i still get an error.
My sql is posted below
SELECT TOP (#range) *
FROM client
WHERE clientId NOT IN
(SELECT TOP (#limit) *
FROM client
ORDER BY clientId)
ORDER BY clientId
The change you need to make to your code is
SELECT TOP (#range) *
FROM client
WHERE clientId NOT IN (SELECT TOP (#limit) clientId /*<-- NOT "*" here */
FROM client
ORDER BY clientId)
ORDER BY clientId
This can also be done by using row_number as below (which performs better depends on the different indexes available and how wide a covering index on the whole query is compared to a narrow one on just clientId.)
DECLARE #lowerlimit int
SET #lowerlimit = #range +#limit;
WITH cte As
(
SELECT TOP (#lowerlimit) * , ROW_NUMBER() OVER (ORDER BY clientId) AS RN
FROM client
ORDER BY clientId
)
SELECT * /*TODO: Your Actual column list*/
FROM cte
WHERE RN >= #limit
Another (similar, slower :) ) way
SELECT * FROM (
select rank() over (ORDER BY yourorder) as rank, *.X
from TableX X
) x2 WHERE rank between 5 and 10