Khairy Abd El-Zaher Khairy Abd El-Zaher - 13 days ago 7
SQL Question

View returns different results from its SELECT

I have a SQL view that returns fewer results than the select inside it, and I don't know why?

The SQL view code:

SELECT cs.customer_id, cs.store_id, cs.join_date, c.name, c.email, c.phone, cs.points,
COALESCE (aph.added_point, 0) AS added_point,
COALESCE (aph.spended_cash, 0) AS spended_cash
FROM dbo.customer_store AS cs
INNER JOIN dbo.customer AS c
ON cs.customer_id = c.id
LEFT OUTER JOIN dbo.added_points_history AS aph
ON cs.customer_id = aph.customer_id AND cs.store_id = aph.store_id


The above query returns 26 rows, but when I select from the view it returns 7 rows only!

The code that created the View:

--Set the options to support indexed views.
SET NUMERIC_ROUNDABORT OFF;
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON;
GO
--Create view with schemabinding.
IF OBJECT_ID ('dbo.customers_store_with_points', 'view') IS NOT NULL
DROP VIEW dbo.customers_store_with_points ;
GO
CREATE VIEW dbo.customers_store_with_points
WITH SCHEMABINDING
AS
SELECT cs.customer_id, cs.store_id, cs.join_date, c.name, c.email, c.phone, cs.points,
COALESCE (aph.added_point, 0) AS added_point,
COALESCE (aph.spended_cash, 0) AS spended_cash
FROM dbo.customer_store AS cs
INNER JOIN dbo.customer AS c
ON cs.customer_id = c.id
LEFT OUTER JOIN dbo.added_points_history AS aph
ON cs.customer_id = aph.customer_id AND cs.store_id = aph.store_id
GO
--Create an index on the view.
CREATE UNIQUE CLUSTERED INDEX IDX_customerId_storeId
ON dbo.customers_store_with_points (customer_id, store_id);
GO


The select statment for getting results from the View:

SELECT TOP 1000 *
FROM [dbo].[customers_store_with_points]
order by store_id

Answer

Identical queries with identical data sources returns the same results.
Either you are querying different databases or your queries are different.

Comments