Showing posts with label views. Show all posts
Showing posts with label views. Show all posts

Monday, March 19, 2012

How can you optimize duplicated work in views?

This one's kind of hard to explain, so I've opted to post a simplified
version of our view that prompted me to ask this question: The
question is re-asked after the view...

create view MainView (
PrimaryKeyID,
SubTotal1,
SubTotal2,
GrandTotal
)
as

select t.PrimaryKeyID,
sum(t1.Total),
sum(t2.Total),
sum(t1.Total) + sum(t2.Total)
from SomeTable t
join CalculationTable t1 on ...
join AnotherCalculationTable t2 on ...

Notice in the 3rd column called "GrandTotal" how it calls the function
"sum" two more times. Common sense tells me that this is not
necessary. in our case it's orders of magnitude worse... Is the query
optimizer smart enough to only call these sums once per row in
"SomeTable"? Common sense tells me that if we were to break the views
apart into two views it would avoid this ineffeciency:

create view InnerView (
PrimaryKeyID,
SubTotal1,
SubTotal2
)
as

select t.PrimaryKeyID,
sum(t1.Total),
sum(t2.Total)
from SomeTable t
join CalculationTable t1 on ...
join AnotherCalculationTable t2 on ...

create view OuterView (
PrimaryKeyID,
SubTotal1,
SutTotal2,
GrandTotal
)
as

select iv.PrimaryKeyID,
iv.Total1,
iv.Total2,
iv.Total1 + iv.Total2
from InnerView

Notice how it appears that we've tricked the optimizer into thinking
there are less operations. So my question is how does views handle
this situation? Does the optimizer treat both version the same? Or is
one faster than the other? Or is there another, faster way? Does
adding levels of views slow down things, or are views simply like
macros and get removed when compiled (I think I've read the latter is
true actually)

Thanks,
Davemalcolm (chakachimp@.yahoo.com) writes:
> create view MainView (
> PrimaryKeyID,
> SubTotal1,
> SubTotal2,
> GrandTotal
> )
> as
> select t.PrimaryKeyID,
> sum(t1.Total),
> sum(t2.Total),
> sum(t1.Total) + sum(t2.Total)
> from SomeTable t
> join CalculationTable t1 on ...
> join AnotherCalculationTable t2 on ...
>
> Notice in the 3rd column called "GrandTotal" how it calls the function
> "sum" two more times. Common sense tells me that this is not
> necessary. in our case it's orders of magnitude worse... Is the query
> optimizer smart enough to only call these sums once per row in
> "SomeTable"? Common sense tells me that if we were to break the views
> apart into two views it would avoid this ineffeciency:

I ran this query in Northwind:

select OrderID, SUM(UnitPrice), SUM(Discount),
SUM(UnitPrice) + SUM(Discount)
from [Order Details]
group by OrderID

When I looked at the query plan, it appears to compute the first two sums
in a stream aggregate, and then computed the last sum as a sclar value,
being the sum of the two sums.

However, this may not at all be applicable to your actual query, since
your expressions may be more complex and not lend themselves to
arithmetic simplifications.

In general, though, I think you can trust the optimizer to do the
right thing. Rewriting the query in steps as you suggested, can just
as well make matters worse, since you could confuse the optimizer.
(Or even worse confuse yourself, so that you get incorrect results.)

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

How can you mass-validate stored procedures, views, etc?

I am looking for a way to validate all objects in the database that is is
possible for in some automated fashion. For instance, if a column is droppe
d
from a table stored procedures that rely on it will fail on the next
execution, but I want to be able to run a process that will reveal that prio
r
to execution. I would want to do that for views and user defined functions
as well. Other than executing every procedure and function and selecting
from every view does anyone know of a way to do this?
I thought I'd just script the objects out for ALTER and run that script
against the database but it appears you can only create an ALTER script one
object at a time through EM and with thousands of objects I really don't wan
t
to go through that.
I created a script that ran sp_recompile against every stored procedure,
then another block that executed every stored procedure without supplying an
y
parameters and that seemed to catch stored procedures that relied on missing
columns. The problem with that is it makes the assumption that the stored
procedure would either fail when no parameters were supplied, or would be
harmless when the stored procedure executed either because it required no
parameters or had defaults for all parameters. Of course this also only
worked for stored procedures and not the functions and views.
I made the mistake of changing a view without realizing that it was used in
a stored procedure and when that stored procedure executed it failed. You
can't depend on the dependencies that SQL maintains since they are not alway
s
correct, so you can't even make note of the dependent objects and selectivel
y
check only those objects without risking missing a dependency.
Any suggestions would be greatly appreciated.Byron (Byron@.discussions.microsoft.com) writes:
> I am looking for a way to validate all objects in the database that is
> is possible for in some automated fashion. For instance, if a column is
> dropped from a table stored procedures that rely on it will fail on the
> next execution, but I want to be able to run a process that will reveal
> that prior to execution. I would want to do that for views and user
> defined functions as well. Other than executing every procedure and
> function and selecting from every view does anyone know of a way to do
> this?
> I thought I'd just script the objects out for ALTER and run that script
> against the database but it appears you can only create an ALTER script
> one object at a time through EM and with thousands of objects I really
> don't want to go through that.
>...
This is indeed a difficult situation, and I don't really think there
is a single good way around it.
The method in the above paragraph is fairly easy to apply: use Generate
Scripts from Enterprise Manager to script the entire database. Then
open the generated script in a an editor and change CREATE PROCEDURE
to ALTER PROCEDURE.
However, you may not catch all errors this way. Say that you have:
INSERT #temp (...)
SELECT ..., missing_column
FROM ...
Because of deferred name resolution, SQL Server will not alert you of the
missing column. It sees that #temp is missing, and will defer compilation
of that statement until #temp has been created, and thus the error will
not occur until run-time.
The approach I use myself is based on the fact that we have all code
under version control. We also have a build tool that goes head over
heels to nullify the effect of deferred name resolution, by creating
all temp tables in an SP before loading the procedure. Thus a missing
column is noticed directly. Furthermore, it's easy for me to build an
empty database from SourceSafe, which will give me a complete sysdepends
that I can rely on.

> I created a script that ran sp_recompile against every stored procedure,
> then another block that executed every stored procedure without
> supplying any parameters and that seemed to catch stored procedures that
> relied on missing columns. The problem with that is it makes the
> assumption that the stored procedure would either fail when no
> parameters were supplied, or would be harmless when the stored procedure
> executed either because it required no parameters or had defaults for
> all parameters. Of course this also only worked for stored procedures
> and not the functions and views.
Our build-and-load tool is available for free download on
http://www.abaris.se/abaperls/. To get started with it, may be overmuch.
However, the toolset in includes a free-standing tool SPTRITEST which
performs essentially the above, but also provides dummy value for all
parameters, so it permits you test far more procedures. It goes without
saying that you should run this on a *copy* of the database, or else
you get a load of junk in it.
And it may still not find all cases of missing columns, since if there
are IF-ELSE branches, you are likely to pass over only one of them.
I also need to add the disclaimer that I wrote it in 6.5 days, and I
have not used it myself for ages.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Monday, March 12, 2012

How can we manually change the scales displayed on ProClarity Perspective Views?

Hi, all here,

Thank you very much for your kind attention.

I still think here should be an ideal place for me to put my post here for help for ProClarity (with SQL Server 2005 Analysis Services)

Would please any expert here give me any guidance and advices for if it is possible for users to change scales displayed on ProClarity Perspective views? And if it is possible, how can we change it?

Thanks a lot in advance for that.

With best regards,

Yours sincerely,

You cannot change the scales of the y & x axis in Perspective.

What you can do is right click on an interesting part of the tool and choose zoom/zoom out.

The scales will automatically change according to this.

HTH

Thomas Ivarsson

|||

Hi, Thomas,

Thank you very much.

With best regards,

Yours sincerely,

|||

Good luck Helen. Perspective is not a chart. Have a look at colour coding and see what you can do.

In this tool you can select leaf level members in a product dimension and colour code them at a highet level, like product categories.

It is used , as an example, to find your products that will sell at high volumes-high margins/high volumes-low margins, low volumes/low margins and low volumes/high margins.

That is way you only have measures on each axis.

HTH

Thomas

|||

Hi, Thomas,

Thank you very much.

With best regards,

Yours sincerely,

Friday, March 9, 2012

How can one find out if two tables can be joinned dynamically

Hi All,

Given a table, is there a way to programmatically find out what other tables and views it can be joinned with? Essentially, given two tables, two views, or a table and a view, I want to be able to find out if they can be joinned. I was able to find related tables with sp_fkeys, but this does not work all the time, and does not work at all with views. I also played with the information_schema but got mixed up and confused quickly.

Any help would be greatly appreciated.

Can you explain what you are trying to do with joining tables dynamically? What is the problem you are trying to solve? It seems very complicated to me. You can use sp_fkeys or INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS or sys.foreign_keys (SQL2005) to get the list of foreign keys and go from there. This will be accurate as long as you have the necessary constraints defined in your schema.

Views do not explicitly have any relationship to tables. You can use WITH SCHEMABINDING option with views but it is different than a foreign key reference. You can use INFORMATION_SCHEMA.VIEW_TABLE_USAGE to get tables that are referenced in a view. There is similar view to get the column usage information.

|||

Umachandar,

Thanks a bunch for the pointers. I am buildinng a reporting application, where users can select columns from a list of tables and views. Naturally, I only want to show tables and views that are related. For example, I know I can join table Orders and view [Order Details Extended], therefore I want to show the two datasources. My problem is that I want to show the relationship dynamically.

I am a little confused with INFORMATION_SCHEMA.VIEW_TABLE_USAGE:

When I run this in Query analyzer, I get a bunch or records, including:

Northwind |dbo |Category Sales for 1997| Northwind |dbo |Product Sales for 1997|

The last column, which is the Table_Name, is [Product Sales for 1997] which is a view! What does this mean? How do I get a list of all tables related to a view? Or vice versa?

Thanks again,

Amine

|||

The usual approach that I have seen taken with this is to come up with your own table that holds the relationship information.

The users start off by selecting one main table to query then as they add data elements from other tables the query builder retrieves the appropriate row and adds that to the query it is building.

MainTable Related Table Relationship

Customers Orders Customers.CustomerID = Sales.CustomerID

Query is bult as follows

SELECT -- whatever columns you select

FROM Customers, Orders

WHERE Customers.CustomerID = Sales.CustomerID

Even though this is not ANSI standard syntax (and I hate seeing joins like this) it is easier to build the string dynamically. If another table is selected then they simply add that to the FROM clause " , CustomerPhone" and to the where clause " AND CustomerPhone.CustomerID = Sales.CustomerID"

|||

Views can reference views or tables. The information schema view goes only one level so you will have to write a recursive query like below to get all dependencies:

with vt
as (
select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
where objectproperty(object_id(quotename(TABLE_SCHEMA) + N'.' + quotename(TABLE_NAME)), 'IsView') = 1
union all
select t2.VIEW_SCHEMA, t2.VIEW_NAME, t1.TABLE_SCHEMA, t1.TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE as t1
join vt as t2
on t1.VIEW_SCHEMA = t2.TABLE_SCHEMA and t1.VIEW_NAME = t2.TABLE_NAME
)
select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from vt
union all
select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
where objectproperty(object_id(quotename(TABLE_SCHEMA) + N'.' + quotename(TABLE_NAME)), 'IsView') = 0
order by VIEW_NAME, TABLE_NAME;

This query is harder to write in SQL Server 2000 but if you know the depth of the dependencies before hand then you can write a single query. Otherwise you can create a multi-statement TVF that simulates above logic.

|||

David,

Thanks for the help. I was trying to avoid doing that. I wanted to only show the tables and views that were related at design time. I guess I could do the "blind" join and if this fails, notify the user.

Thanks

Amine

|||

Awsome. This will get me going.

Thanks a lot!

|||

Hi Again,

I ran this query in SQL 2005 and it worked OK, but does not run in MSDE or SQL 2000. Any ideas why? I get

Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'with'.

|||The query put forth by one of the other illustrious posters uses a Common Table Expression (CTE) which is a new feature for SQL 2005. He does mention that for SQL 2000 you will need a different plan of attack.|||

Hi

Try it in SQL 2000

select t2.VIEW_SCHEMA, t2.VIEW_NAME, t1.TABLE_SCHEMA, t1.TABLE_NAME
from
(select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
where objectproperty(object_id(quotename(TABLE_SCHEMA) + N'.' + quotename(TABLE_NAME)), 'IsView') = 1) t2 inner join
INFORMATION_SCHEMA.VIEW_TABLE_USAGE as t1
on t1.VIEW_SCHEMA = t2.TABLE_SCHEMA and t1.VIEW_NAME = t2.TABLE_NAME

Irfan

How can one find out if two tables can be joinned dynamically

Hi All,

Given a table, is there a way to programmatically find out what other tables and views it can be joinned with? Essentially, given two tables, two views, or a table and a view, I want to be able to find out if they can be joinned. I was able to find related tables with sp_fkeys, but this does not work all the time, and does not work at all with views. I also played with the information_schema but got mixed up and confused quickly.

Any help would be greatly appreciated.

Can you explain what you are trying to do with joining tables dynamically? What is the problem you are trying to solve? It seems very complicated to me. You can use sp_fkeys or INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS or sys.foreign_keys (SQL2005) to get the list of foreign keys and go from there. This will be accurate as long as you have the necessary constraints defined in your schema.

Views do not explicitly have any relationship to tables. You can use WITH SCHEMABINDING option with views but it is different than a foreign key reference. You can use INFORMATION_SCHEMA.VIEW_TABLE_USAGE to get tables that are referenced in a view. There is similar view to get the column usage information.

|||

Umachandar,

Thanks a bunch for the pointers. I am buildinng a reporting application, where users can select columns from a list of tables and views. Naturally, I only want to show tables and views that are related. For example, I know I can join table Orders and view [Order Details Extended], therefore I want to show the two datasources. My problem is that I want to show the relationship dynamically.

I am a little confused with INFORMATION_SCHEMA.VIEW_TABLE_USAGE:

When I run this in Query analyzer, I get a bunch or records, including:

Northwind |dbo |Category Sales for 1997| Northwind |dbo |Product Sales for 1997|

The last column, which is the Table_Name, is [Product Sales for 1997] which is a view! What does this mean? How do I get a list of all tables related to a view? Or vice versa?

Thanks again,

Amine

|||

The usual approach that I have seen taken with this is to come up with your own table that holds the relationship information.

The users start off by selecting one main table to query then as they add data elements from other tables the query builder retrieves the appropriate row and adds that to the query it is building.

MainTable Related Table Relationship

Customers Orders Customers.CustomerID = Sales.CustomerID

Query is bult as follows

SELECT -- whatever columns you select

FROM Customers, Orders

WHERE Customers.CustomerID = Sales.CustomerID

Even though this is not ANSI standard syntax (and I hate seeing joins like this) it is easier to build the string dynamically. If another table is selected then they simply add that to the FROM clause " , CustomerPhone" and to the where clause " AND CustomerPhone.CustomerID = Sales.CustomerID"

|||

Views can reference views or tables. The information schema view goes only one level so you will have to write a recursive query like below to get all dependencies:

with vt
as (
select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
where objectproperty(object_id(quotename(TABLE_SCHEMA) + N'.' + quotename(TABLE_NAME)), 'IsView') = 1
union all
select t2.VIEW_SCHEMA, t2.VIEW_NAME, t1.TABLE_SCHEMA, t1.TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE as t1
join vt as t2
on t1.VIEW_SCHEMA = t2.TABLE_SCHEMA and t1.VIEW_NAME = t2.TABLE_NAME
)
select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from vt
union all
select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
where objectproperty(object_id(quotename(TABLE_SCHEMA) + N'.' + quotename(TABLE_NAME)), 'IsView') = 0
order by VIEW_NAME, TABLE_NAME;

This query is harder to write in SQL Server 2000 but if you know the depth of the dependencies before hand then you can write a single query. Otherwise you can create a multi-statement TVF that simulates above logic.

|||

David,

Thanks for the help. I was trying to avoid doing that. I wanted to only show the tables and views that were related at design time. I guess I could do the "blind" join and if this fails, notify the user.

Thanks

Amine

|||

Awsome. This will get me going.

Thanks a lot!

|||

Hi Again,

I ran this query in SQL 2005 and it worked OK, but does not run in MSDE or SQL 2000. Any ideas why? I get

Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'with'.

|||The query put forth by one of the other illustrious posters uses a Common Table Expression (CTE) which is a new feature for SQL 2005. He does mention that for SQL 2000 you will need a different plan of attack.|||

Hi

Try it in SQL 2000

select t2.VIEW_SCHEMA, t2.VIEW_NAME, t1.TABLE_SCHEMA, t1.TABLE_NAME
from
(select VIEW_SCHEMA, VIEW_NAME, TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
where objectproperty(object_id(quotename(TABLE_SCHEMA) + N'.' + quotename(TABLE_NAME)), 'IsView') = 1) t2 inner join
INFORMATION_SCHEMA.VIEW_TABLE_USAGE as t1
on t1.VIEW_SCHEMA = t2.TABLE_SCHEMA and t1.VIEW_NAME = t2.TABLE_NAME

Irfan

Wednesday, March 7, 2012

How can I use the GetSchema to get a list of only user tables and views.

How can I use the GetSchema method new in 2.0 to get a list of only user tables and views.

By defautl, GetSchema will return tables that belong to dbo schema. In SQL2005, all system tables/views belong to sys schema. If you want to get schema for objects that belong to a specific user, you should set the 2nd restriction value to the owner name. For example:

string connectionString = "Data Source=(local);Database=master;Integrated Security=SSPI;";


using (SqlConnection connection =
new SqlConnection(connectionString))
{
//Connect to the database, and then retrieve the
//schema information.
connection.Open();
string[] restrictions = new string[4];
restrictions[1] = "iori";
DataTable table = connection.GetSchema("Tables", restrictions);

// Display the contents of the table.
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}

Console.WriteLine("Press any key to continue.");


}

For more info, please go to this website:

http://msdn2.microsoft.com/en-us/library/ms254934.aspx

|||

When I changed the string as follows to access db. I am getting the error. Please help! thanks

myConnectionString ="Provider=Microsoft.Jet.Oledb.4.0; Data Source=c:AjaxSureAcc/App_Data/AccountInfo.mdb";

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.ArgumentException: Keyword not supported: 'provider'.

|||

never mind the above. I figured it out. I should have been using oleDBConnection