Why am I getting a different numbers of distinct ids in those queries?
USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';
select locations.*, T.c.value('.','nvarchar(max)') from
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
) as locations cross apply @myXml.nodes('(/lol)') T(c);
select mytable.* , T.c.value('.','nvarchar(max)') from
(
select newid() as Id
union
select newid()
) as mytable cross apply @myXml.nodes('(/lol)') T(c);
I've been trying to figure out why these two return a different amount of distinct ids... Is that a bug in optimization?
Code Snippet
USE AdventureWorks go Declare @myXml as xml set @myXml = ' <lol>omg</lol> <lol>rofl</lol> ';
WITH locations as ( select newid() as Id from Production.ProductModel where ProductModelID in (7, 8) ) select locations.*, T.c.value('.','nvarchar(max)') from locations cross apply @myXml.nodes('(/lol)') T(c);
with mytable as ( select newid() as Id union select newid() ) select mytable.* , T.c.value('.','nvarchar(max)') from mytable cross apply @myXml.nodes('(/lol)') T(c);
Hi... I'm reading the MS Press 70-442 Self-Paced Training kit, and I'm having problems with this example. I'd like help getting it to work correctly, or understand why it is isn't working the way I planned.
On page 67, the lab is about the APPLY operator (CROSS APPLY and OUTER APPLY). I first have to input a sample table-valued function into the AdventureWorks database:
Code Block CREATE FUNCTION fnGetAvgCost(@ProdID int) RETURNS @RetTable TABLE (AvgCost money) AS BEGIN WITH Product(stdcost) AS ( SELECT avg(standardcost) as AvgCost FROM Production.ProductCostHistory WHERE ProductID = @ProdID ) INSERT INTO @RetTable SELECT * FROM Product RETURN END
and then run a sample T-SQL statement
Code Block SELECT p.Name, p.ProductNumber, Convert(varchar, cost.AvgCost,1) AS 'Average Cost' FROM Production.Product p CROSS APPLY fnGetAvgCost(p.ProductID) AS cost WHERE cost.AvgCost IS NOT NULL ORDER BY cost.AvgCost desc
My problem is with the WHERE clause... According to page 56, CROSS APPLY returns only rows from the outer table that produces a result set, so why do I need to explicitly filter NULL values?
When I remove the WHERE clause, the query retrieves lots of NULL AvgCost values.
Again, according to page 56, it is the OUTER APPLY that returns all rows that return a result set and will include NULL values in the columns that are returned from the table-valued function.
So, in short, I don't see the difference between CROSS APPLY and OUTER APPLY, using this example, when I remove the WHERE clause?
(Please refrain from introducing another example into this question.)
I'm attempting to leverage SQL's new 'APPLY" operator and I guess I don't fully understand it proper usage.
This is a relatively simple request, first i want to count the models produced within a valid period of time. The first 'Cross Apply' gets the valid starting and ending dates and looks ups the number of models produced for the period of time. This section of code works perfectly fine.
The problem appears to be with the second "Cross Apply". What I'm attempting to accomplish is to count all models produced, regardless of time frame.
When executed the query appears to go into an loop and I end up canceling out the request.
Any ideas where I went wrong?? Any help is greatly appreciated!
select b1.model as Model ,b1.MinDate as Mfg_Str_Date ,b1.MaxDate as Mfg_End_Date ,Count(b2.Model+B2.Serial) as Mfg_Date_Valid ,Count(b3.Model+B3.Serial) as All_Units
from (select b.model, min(b.build_date) as MinDate ,max(b.build_date) as MaxDate from etbl_models_Serial as b group by b.model) as b1
--These are Units produced within Valid Window cross apply (select b2.model,b2.Serial from etbl_Production as b2 where b2.Model = b1.Model and b2.Mfg_Date between b1.MinDate and b1.MaxDate) as b2
--These are all units produced cross apply (select b3.model,b3.Serial from etbl_Production as b3 where b3.Model = b2.Model) as b3
Group by b1.Model, b1.MinDate, b1.MaxDate Order by b1.Model
Select top 1000 a.EmployeeID,b.* from #TmpActiveEmployeesWSeverance a cross apply dbo.fn_Severance_AccountItemsTable(a.EmployeeID,a.BenefitTypeID,null,null,null,null) b order by a.EmployeeID,a.BenefitTypeID
It runs 4 seconds
If I try to insert the results into anything It runs > 5 minutes (I have yet to let it finish)
I have tried the two following pieces of code, both with the same results
Select top 1000 a.EmployeeID,b.* into #Tmp from #TmpActiveEmployeesWSeverance a cross apply dbo.fn_Severance_AccountItemsTable(a.EmployeeID,a.BenefitTypeID,null,null,null,null) b order by a.EmployeeID,a.BenefitTypeID
--and Insert Into TRP_ActiveEmployeesWSeverance (EmployeeID ,PK ,BeginningBalance ,BenefitInterestRowID ,BenefitInterestID ,BenefitTypeID ,DateReceived ,InvoiceDate ,Amount ,Hours ,Fraction1 ,Fraction2 ,Interest ,InterestAmount ,StartDate ,EndDate ,PeriodApplied ,Offset ,Reserve ,Account ,BenefitClosedID ,PaidOut ,ClosedAccount ,ai ,ClosedDate ,StartAgain ,PartialDividend ,PartialFraction ,SameDateCount) Select top 1000 a.EmployeeID,b.* from #TmpActiveEmployeesWSeverance a cross apply dbo.fn_Severance_AccountItemsTable(a.EmployeeID,a.BenefitTypeID,null,null,null,null) b order by a.EmployeeID,a.BenefitTypeID
SELECT res.res_id, sub.value('(./@id)[1]', 'char(2)') id FROM vwResult res CROSS APPLY report.nodes('/clue_personal_auto/report/search_dataset/subjects/*') report(sub)
It works just fine in SQL Query.After placing this into a view in SSDT November 2012 update, I get a compilation error.
I am doing a report that uses paging and in order to optimize it, i used row_number() so i could make it return x rows per page, so, in order to compute the number of pages needed, i have to count the total number of rows, which gets very slow because i'm using a cross apply with a table-valued function. Is there any way so i can get the number of rows processed by row_number() so i dont have the need to do count?
Hey guys. This is one of the queries pasted from BOL. I'm having problems excuting this query. The problem lies in the CROSS APPLY part. When I copy this query and run it in SSMS, it gives me an error saying 'Incorrect syntax near .' It doesn't like the qs.sql_handle part. If I remove that and pass the actual handle in for some query, it works. Can someone please tell me what I'm doing wrong?????? Also, I've sp1 installed on my SQL Server 2005 Enterprise, just in case if this matters. Below is the query pasted which is giving me problems. Thank you.
SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],
The result I want is the unique rows from columns:
PupilPersonId, EducationTypeId,VehicleTypeId AND there MAX EducationDate SELECT er1.* FROM EducationResult er1 INNER JOIN ( SELECT er.PupilPersonId, er.EducationTypeId, er.VehicleTypeId, MAX(er.EducationDate) as EducationDate
[Code] ....
I like to know is there another approach with CTE and or Cross Apply I can use instead?
ChangeID ChangeDate EquipmentID ModuleID EquipStatus 1 12/9/08 230 1789 Normal 2 13/9/08 450 1245 Normal 3 17/9/08 230 1789 Open 4 21/9/08 230 1899 Open 5 21/9/08 450 1674 Normal 6 22/9/08 450 2364 Normal
Given a date, what module was each equipment item in on that date?How do I get the date of the nearest previous event from a list like this? I got a query from one of the post in this Forum only using Cross Apply to find the nearest record from the above table based on Date i.e.
SELECT outerT.* FROM your_table AS outerT CROSS APPLY ( SELECT TOP 1 equipment_id , change_date FROM your_table AS innerT WHERE innerT.change_date <= @point_in_time AND innerT.equipment_id = outerT.equipment_id ORDER BY change_date DESC ) AS applicable_records WHERE applicable_records.change_date = outerT.change_date
The problem is I need to get this query without using Cross Apply as i need to use the same for the LINQ which doesn't support Cross Apply.
I was reading Kenneth Fisher's and Dwain Camps' articles on unpivoting using cross apply... And I can actually get them to work....
CREATE TABLE #TxCycle( Cycle INT NOT NULL, PatientID INT NOT NULL, ALOPECIA TINYINT, Causality1 TINYINT, Relatedness1 TINYINT,
[Code] ....
The one thing I was wondering was this: how do I extract the symptom names from the field list without knowing them all beforehand? Dwain does this
-- DDL and sample data for UNPIVOT Example 2 CREATE TABLE #Suppliers (ID INT, Product VARCHAR(500) ,Supplier1 VARCHAR(500), Supplier2 VARCHAR(500), Supplier3 VARCHAR(500) ,City1 VARCHAR(500), City2 VARCHAR(500), City3 VARCHAR(500))
Can this be adapted if you don't know all the column names beforehand? (Likely not). Back in the dark ages, when I was working on a database like this, it was in Access, and I could loop over the fields collection and evaluate each field name. (Yes, I know you're not supposed to store information in field names, but I inherited that mess!)
See sample data below. I'm trying to count the number of occurrences of strings stored in table @word without a while loop.
DECLARE @t TABLE (Id INT IDENTITY(1,1), String VARCHAR(MAX))
INSERT INTO @t SELECT 'There are a lot of Multidimensional Expressions (MDX) resources available' AS String UNION ALL SELECT 'but most teaching aids out there are geared towards professionals with cube development experience' UNION ALL
I'm unable to reproduce the error. when they upgrade their OS and SQL EXPRESS to a more recent version the error disappears.
The error is: Incorrect syntax near '.'
the query in question resembles this:
Select column1, column2 from Table1 T cross apply function(t.column4,t.column5) F where column3 = 'XXXX'
I made sure that the compatibility level is greater than 90 this error is happening on SQL2005 SP2 as well as SQL2008 with SP2 (but not all clients are suffering from the same problem)
Can it be the .net framework? Although the machines had .net framework 3.52.
Can the OS be an issue? The OS' seem to be old, Windows Server 2008 SP2
I've tried to reproduce the error by setting up virtual machines with same OS and SQL but, again, can't reproduce.
I am using CROSS APPLY instead of UNPIVOT to unpivot > one column. I am wondering if I can dynamically replace column names based on different tables? The example code that I have working is based on the "Allergy" table. I have thirty more specialty tables to go. I'll show the working code first, then an example of another table's columns to show differences:
select [uplift specialty], [member po],[practice unit name], [final nomination status] ,[final uplift status], [final rank], [final uplift percentage] ,practiceID=row_number() over (partition by [practice unit name] order by Metricname) ,metricname,Metricvalue, metricpercentilerank
[code]....
Rheumatology Table:The columns that vary start with "GDR" and [GDR Percentile Rank] so I'm just showing those:
create table a (id int, name varchar(10)); create table b(id int, sal int); insert into a values(1,'John'),(1,'ken'),(2,'paul'); insert into b values(1,400),(1,500);
select * from a cross apply( select max(sal) as sal from b where b.id = a.id)b;
Below is the result for the same:
idname sal 1John500 1ken500 2paulNULL
Now I'm not sure why the record with ID 2 is coming using CROSS APPLY, shouldn't it be avoided in case of CROSS APPLY and only displayed when using OUTER APPLY.
One thing that I noticed was that if you remove the Aggregate function MAX then the record with ID 2 is not shown in the output. I'm running this query on SQL Server 2012.
Dear Folks, can you please tell me, how many newid's can be generated by an sql server instance? and the newid generated by one instance can possibly be generated by another instance ? please give me brief regarding this
Is there a limitation of using:set @sessionID = NEWID()would there be a simular NEWID() being generated if used in a databaseapplication.Eugene Anthony*** Sent via Developersdex http://www.developersdex.com ***
when you use newid() is that a new uniqueidentifier for the database or for the table???I have a changelog that captures newly created users first and gives them a newid, then i want to approve that change and copy the newid generated for that user into the user table. Will I run into duplicate id's that way???
Excuse my ignorance because I don't do advance db related programming,but have no other choice at the moment. My experience is limited tosimple queries.I need to have the following query display the recordset in random orderbased on RecordID (unique key) if possible. I tried the ORDER BY NewID()at the end and it generated an error (ORDER BY items must appear in theselect list if SELECT DISTINCT is specified.) I guess because of the subquery. I would also like for the recordset to display a different 10records on each hit to the page, not just the same 10 records in randomorder. I wasn't sure if the SELECT commands I have in place aresufficient for this task.Thanks in advance for any assistance.SELECT DISTINCTTOP 10 dbo.ShowcaseRides.RecordID,dbo.ShowcaseRides.CustomerID, dbo.ShowcaseRides.PhotoLibID,dbo.ShowcaseRides.Year,dbo.ShowcaseRides.MakeShowcase,dbo.ShowcaseRides.ModelShowcase, dbo.ShowcaseRides.VehicleTitle,dbo.ShowcaseRides.NickName,dbo.ShowcaseRides.SiteURL,dbo.ShowcaseRides.ShowcaseRating, dbo.ShowcaseRides.ShowcaseRatingImage,dbo.ShowcaseRides.ReviewDate,dbo.ShowcaseRides.Home,dbo.ShowcaseRides.EntryDate, dbo.Customers.UserName,dbo.Customers.ShipCity, dbo.Customers.ShipRegion,dbo.Customers.ShipPostalCode,dbo.Customers.ShipCountry, dbo.Customers.LastName,dbo.Customers.FirstName, dbo.Customers.MemberSince,dbo.ShowcaseRides.Live,dbo.ShowcaseRides.MemberLive, dbo.Accessories.Make,dbo.Accessories.Model, Photos.PathFROM dbo.ShowcaseRides INNER JOINdbo.Customers ON dbo.ShowcaseRides.CustomerID =dbo.Customers.CustomerID INNER JOINdbo.Accessories ON dbo.ShowcaseRides.MakeShowcase= dbo.Accessories.MakeShowcase ANDdbo.ShowcaseRides.ModelShowcase =dbo.Accessories.ModelShowcase INNER JOIN(SELECT MIN(dbo.ShowcasePhotos.PhotoPath)AS Path, RecordIDFROM dbo.ShowcasePhotosGROUP BY RecordID) Photos ONdbo.ShowcaseRides.RecordID = Photos.RecordID INNER JOINdbo.ShowcasePhotos ON Photos.Path =dbo.ShowcasePhotos.PhotoPathWHERE (dbo.ShowcaseRides.MemberLive = 1) AND (dbo.ShowcaseRides.Live= 1) AND (dbo.ShowcaseRides.MakeShowcase = @MMColParam)ORDER BY dbo.ShowcaseRides.EntryDate DESCRegards,Darin L. MillerParadyse Development~-~-~-~-~-~-~-~-~-~-~-~-~-~-"Some things are true whether you believe them or not." - Nicolas Cagein City of Angels
I have a view which at the moment has no unique identifier on each record. When I try adding a column definition to the view such as NEWID() as TransactionId, the view then cannot 1) be selected into a temporary table, or 2) queried on other columns in the table. In either case I end up with an empty result set.
I believe I have a way around this for my purpose, which was principally testability. However, can anyone enlighten me as to how and why this happens?
I have an application being developed using SQL server. The data is captured at various remote areas and the SQL servers are not physically connected to each other.
Periodically either through a replication / backup process i plan to update the data from various servers into a central database.
Can i use the NewID() function to generate a unique ID which i can use as a primary key that would not be duplicated across all these servers?
if not Please suggest a solution to maintain the uniqueness of the transaction.
I have 2 tables, Artists and Artworks. I have a query:
SELECT TOP (4) dbo.Artists.ArtistID, dbo.Artists.FirstName + ' ' + dbo.Artists.LastName AS FullName, dbo.Artworks.ArtworkName, dbo.Artworks.Image FROM dbo.Artists INNER JOIN dbo.Artworks ON dbo.Artists.ArtistID = dbo.Artworks.ArtistID ORDER BY NEWID()
This query returns random images, but the artists are sometimes repeated. I would like to have DISTINCT Random Artists returned, each with a random image. I tried various subqueries, but I just get error messages. Any help would be appreciated. Thnks,
Is it possible to use NEWID() as a parameter to a stored procedure inSQL Server 2000. I keep getting a "Line 1: Incorrect syntax near ')'"error.ALTER PROCEDURE dbo.StoredProcedure1(@x uniqueidentifier)AS/* SET NOCOUNT ON */RETURNStoredProcedure1 NEWID()go"Line 1: Incorrect syntax near ')'"Thanks in advance
Hello.So the scenario is a little complicated.I am joining two tables.Table 1 is derived; it has one row; it has a column based from newid()Table 2 joins to table 1 and reuses the newid() value from table 1 in table 2's rowsBecause there is only one row in Table 1, the value of newid() REPEATS in Table 2The bug is that the NewId() value from Table1 is REGENERATED with every Table 2 record.I created a blog about this because it takes a code sample to demonstrate:http://jerrytech.blogspot.com/2008/04/sql-2005-tsql-bug-with-newid-in-derived.html
Hi There, I'm having a problem retreiving the auto generated Guid after inserting anew record with NEWID(), my stored proc is as follows:SET @uiTransactionID = NEWID() INSERT INTO Transactions (uiTransactionID) VALUES (@uiTransactionID) IF @@ERROR = 0 AND @@ROWCOUNT = 1 BEGIN SELECT @uiTransactionID AS '@@GUID' RETURN 0 END And the return on my insert statement is: command.ExecuteNonQuery();m_uiTransactionID = (Guid)command.Parameters["RETURN_VALUE"].Value; I can never retreive the newly generated Guid, can onyone spot where i'm going wrong? Many thanks Ben