Showing posts with label procedure. Show all posts
Showing posts with label procedure. Show all posts

Monday, March 26, 2012

Joins query help

Hi all,

Just after some help with a query (Stored Procedure) I've managed to get wrapped round my head.

The DB is as such:

COMPANY
Company_id
Company_name

COMPANY_GROUP
Group_id
Group_name

USER
User_id
User_name

Bridging tables

COMPANY_GROUP_BRIDGE
company_id
group_id

USER_COMPANY_BRIDGE
user_id
company_id

Basically, the only parameter I have for the query is a User_id.

I need to get the Group linked to the User and return all the companies within that group.

I'vetried reading up on all the join types again but have just got thiscompletely wrapped round my neck. I keep thinking along the lines ofSELECT all the companies linked to all the groups linked to all thecompanies linked to the User_id :s I must be able to dothis without using two Company tables...?

Any help much appreciated,

Pete

I don't think the table structure is good. You only need one bridge table in stead of two. In this one table, just put company_id, group_id, and user_id together. Otherwise, you will join too much.

|||

There seems to be a contradiction here. You wrote

"I need to get the Group linked to the User and return all the companies within that group."

But you don't have any table that stores the users assigned to a company group.

In case a user belongs to a group and not a company, create a table that will store user id and group id.

Then you can write a query to get all the companies linked to the group to which the user belongs

|||

Cheers for the replies guys, you've pretty much asserted what I've been dreading all along.

The DB is a complete messed up and looks like I'm gonna have to completely overhaul it :/

(BTW:It is not currently possible for a user to be linked to a group but nota company. The groups are not in there for this purpose - In fact Imnot sure why there are there!)

|||

Hmm OK,

Any reccomendations on what a DB 'should' look like based on thisveryextremely light spec:

A Distributor can have many Resellers
A Reseller can have many Groups
A Group can have many Companies
A Company can have many Users
A User may belong to many Companies

(Looking at it - it has been designed so that a Company can belong to many Groups but I dont think that would ever happen )

I think the problem originally was that a User may belong to certaincompanies within a group but not neccessarilly all of them - hence theUser is linked to individual companies rather than a Group.

Also, in the admin backend the problem is which companies to show for options such as edit etc.

A Group Administrator may see all the companies within a group but aCompany Administrator may only see the Companies they are associatedwith in the bridge table. Looks like I'll need the User's'access_level' in all the SProcs.

OK, back to basics. My head hurts.

|||

It is often helpful to think about it this way: every noun is a table, so:

Distributor table
Reseller table
Group table
Company table
User tables

A Distributor can have many Resellers
A Reseller can have many Groups
A Group can have many Companies
A Company can have many Users
A User may belong to many Companies

Every time you write, "can have many" it implies the presence of a foreign key (FK). Many-to-many relationships (company-user) requires a cross reference table. So:

Distributor table
- Distributor ID (probably an identity column)
- Reseller ID (FK to Reseller table)
- other fields

Reseller table
- Reseller ID (probably an identity column)
- Group ID (FK to Group table)
- other fields

Group Table
- Group ID (probably an identity column)
- Company ID (FK to Company table)
- other fields

Company Table
- Company ID (probably an identity column)
- other fields

User Table
- User ID (probably an identity column)
- other fields

Company-User-Cross-Reference Table
- Company ID (FK to Company table)
- User Id (FK to User Table)
NOTE: The Primay Key of this table is Company ID + User ID

|||

Hi David, thanks for that!

That does reassure me that I am on the right track with my structure as that is the way I have gone about things.

I think I rushed into it though and ended up creating astructure where a group could belong to multiple resellers which iswrong (and also that resellers could belong to multiple Distributorswhich is also wrong) So I shall remove the cross-reference tables forDistributors and Resellers.

However, I think I need to make the following minor changes to your suggestion:

Group Table
- Group ID (probably an identity column)
- other fields

Company Table
- Company ID (probably an identity column)
- Group ID (FK to Group table)
- other fields

This is so that a Group can have many Companies. (and a Company can only belong to one group)

(And also changes so Reseller Table contains the DistributorID and the Group table contains the ResellerID)

Could you just clear something up for me though please: Youappear to have placed the CompanyID in the Group table - would this notmean that a Group can only have one company? Is it not correct to putthe GroupID in the Company table. Then each Company can be linked to aparticular group?

What do you think..?

Again, thanks for your advice it is greatly appreciated,

Pete

|||

pete_m:

Could you just clear something up for me though please: You appear to have placed the CompanyID in the Group table - would this not mean that a Group can only have one company? Is it not correct to put the GroupID in the Company table. Then each Company can be linked to a particular group?

Yes, you're right, I was doing this too fast. I think you have the idea now.

Monday, March 19, 2012

joining sysprocesses with fn_get_sql

ok, I have a requirement where I need to get a list of sql commands currently being blocked.
This is very easy to do via stored procedure, and I have it working well using a vb.net console app to fire it off.

Trouble is, I need to ship it to different offices on an ad hoc basis. I don't want to install a stored procedure on each site because it'll be a one off job and there is not likely to be anyone available who would know how to even install a new sp. So, I thought I'd try and pull back the sql commands via a select statement, joining together sysprocesses and the fn_get_sql udf. This returns a table, so I presumed I could join the two together using a subquery via the sql_handle with something like this :

SELECT sql_handle,
(
SELECT top 1 [text] FROM ::fn_get_sql(sysprocesses.sql_handle)
) as sqlcommand

FROM master..sysprocesses

The error back is incorrect syntax near 'sysprocesses'. I can't see if I'm doing anything obvious wrong.

Anyone any ideas? I'm using SQL Server 2000 sp3.A BOL example for using fn_get_sql:
DECLARE @.Handle binary(20)SELECT @.Handle = sql_handle FROM sysprocesses WHERE spid = 52SELECT * FROM ::fn_get_sql(@.Handle) HTH|||thanks for your reply, however, that will only work in a stored procedure.
I won't be able to install a sp, as it needs to be completely standalone.
I'm trying to find a one-hit SQL query to do the job. It should work, but it doesn't.

cheers,

Joining one database table with other database table in stroed procedures.

Hi All,
I need to perform a join on table1 of database1 with table2 or database2, in a stored procedure and return to my web application.. For this I'm providing execute permission on stored procedure, in database1 and "SELECT" permission on database2 table 2, to my database webuser.
Is there any way ( Another stored procedure in database2), i can get join on two tables without SELECT permission right on table2 ( or table1).
Purely using stored procedures. If so how?Normally you only need to grant execute permission on a stored procedure not select permission on the underlying tables.

Past that I would setup a sp to on database1 to return the data and make sure the webuser has an a security path from database1 to database2. How do yo uhave security setup for this user on databse1 and database2?|||Hi Paul,
Thanks, What is meant by security path? I didnot get ur point.
User have only public permission on both databases. Is it not enough? I do have execute permission on sp1 (Stored Procedure) in database1.
but in sp1 I have a select statement which is a join on database2 table-'table2'. When I tried to execute sp1 from web application only with execute permission on sp1-
I got an error as Webuser does not have 'SELECT' permission on table2 of database2. So I provided it and sp1 worked fine. But I don't want to use a SELECT permission- What is alternate, for the join.
sp1 has simple
SELECT *
FROM database1.dbo.table1 t1
INNER JOIN database2.dbo.table2 t2
ON (t1.col1 = t2.col1)

Originally posted by Paul Young
Normally you only need to grant execute permission on a stored procedure not select permission on the underlying tables.

Past that I would setup a sp to on database1 to return the data and make sure the webuser has an a security path from database1 to database2. How do yo uhave security setup for this user on databse1 and database2?|||by security path I was refering to how a user gets authenticated on server2 when making a connection from server1.

You might try using OPENQUERY to call a stored procedure on server2 and use the results to join to a table on server1. I haven't had the need for this in the past so I am working on theory here. Check BOL for usage on OPENQUERY, they have some good examples.|||When calling a stored proc from database 1, you need execute privs on the proc. You do not need to give the user privs on the table itself as long as it is in database 1, too. If database 2 is owned by the same user that is the owner of database 1, you do not need explicit permissions on the object in table 2 accessed by the proc. However, if the database owners are different for the two databases, the user calling the proc must have explicit permissions in the second database.

If need be, you can change the database owner by:

EXEC sp_changedbowner 'username'

Execute this in the database you want to change.|||Well Both databases are on same server. Is OPENQUERY solve in this case too?|||Originally posted by soumyag
Well Both databases are on same server.

It doesn't matter what server they are on, the owner of the databases is what matters. You can have multiple databases on the same server with different owners. In query analyzer, run:

sp_helpdb

It will list the owner for each of the databases. If the owner is different, run sp_changedbowner to set them the same.|||Hi,
Both are on same server, but owned by different users. And I don't have any right to change the dbowners But how it will help in writing a join on tables. What is other alternative way to solve this problem.
Thanks.

Originally posted by bglass

It doesn't matter what server they are on, the owner of the databases is what matters. You can have multiple databases on the same server with different owners. In query analyzer, run:

sp_helpdb

It will list the owner for each of the databases. If the owner is different, run sp_changedbowner to set them the same.

Joining Excel Database with MSDE Database Table, & Import

Looking for the basic procedure to join an Excel spreadsheet with a table fr
om a database running on MSDE, and then updating the MSDE table with select
columns of info from the Excel spreadsheet. I believe the first set of synt
ax will join the file with
MSDE table, and the second set of syntax will run the import/update. If you
can assist, please advise. Thank you in advance.Here is the code how to link Excel sheet to SQL Server:
/* Excel as a linked server */
/* Assuming we have an Excel file 'D:\testi\Myexcel.xls'
with following data in the first sheet:
id name
1 a
2 b
3 c
*/
EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'D:\testi\Myexcel.xls',
NULL,
'Excel 5.0'
EXEC sp_addlinkedsrvlogin 'ExcelSource', 'false'
EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource
SELECT *
FROM ExcelSource...Sheet1$
CREATE TABLE test_excel
(id int,
name varchar(255))
GO
INSERT INTO test_excel
SELECT *
FROM ExcelSource...Sheet1$
SELECT *
FROM test_excel
/* Now define two ranges in Excel on the 2nd sheet as tables */
/* Select the range, Insert->Name->Define */
/* Note: sp_tables_ex does not recognize the defined tables */
/* We can still refer to the tables explicitly */
EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource
SELECT *
FROM ExcelSource...Table1
SELECT *
FROM ExcelSource...Table2
-- Dejan Sarka, SQL Server MVPAssociate MentorSolid Quality LearningMore
than just Trainingwww.SolidQualityLearning.com"G. Benson"
<anonymous@.discussions.microsoft.com> wrote in message
news:E7453061-6084-4E62-9759-C06341C28CAC@.microsoft.com...
> Looking for the basic procedure to join an Excel spreadsheet with a table
from a database running on MSDE, and then updating the MSDE table with
select columns of info from the Excel spreadsheet. I believe the first set
of syntax will join the file with MSDE table, and the second set of syntax
will run the import/update. If you can assist, please advise. Thank you in
advance.|||Dejan, thank you for your expertise. So I fully understand your solution, a
few questions for you:
? am I running each section of SQL code from within Enterprise Manager
? it has been previously suggested that I should be using DTS for these ty
pes of updates -any thoughts
? if id# exists in both the Excel file and in the SQL database (and is use
d as the common relation) -my only objective is to update a blank column of
names in the SQL database with the values of names from the Excel file -are
all of these steps necessar
y for this type of simple update
I am also a novice when it comes to SQL -could you offer a brief explainatio
n of the function behind each section of SQL statements.
Thanks again.|||Dejan, thank you for sharing your expertise. I apologize, but I am a novice
in this area and would like to ask for your clarification on the following:
? my only objective is to use the id field as the link between the Excel f
ile and the SQL database, and simply update a column of blank names in the S
QL database to the column of names located in the Excel file -are all of the
se commands you provided re
quired/complete to accomplish this task
? would it be possible for you to explain what each section of your SQL co
mmands actually performs
? are each of these commands executed exclusively in the Enterprise Manage
r
? I have been told that if I were going to perform this task repeatedly, I
should be using DTS -could you advise (is this part of Enterprise Manager),
or maybe there is another tool you might suggest which simplifies this link
/update procedure for novic
es (ie Adobe GoLive writes HTML code for non-programmers)
Thank you again for your time and knowledge.|||Dejan, thank you for sharing your expertise. I apologize, but I am a novice
in this area and would like to ask for your clarification on the following:
? my only objective is to use the id field as the link between the Excel f
ile and the SQL database, and simply update a column of blank names in the S
QL database to the column of names located in the Excel file -are all of the
se commands you provided re
quired/complete to accomplish this task
? would it be possible for you to explain what each section of your SQL co
mmands actually performs
? are each of these commands executed exclusively in the Enterprise Manage
r
? I have been told that if I were going to perform this task repeatedly, I
should be using DTS -could you advise (is this part of Enterprise Manager),
or maybe there is another tool you might suggest which simplifies this link
/update procedure for novic
es (ie Adobe GoLive writes HTML code for non-programmers)
Thank you again for your time and knowledge.
-- G. Benson wrote: --
Looking for the basic procedure to join an Excel spreadsheet with a table fr
om a database running on MSDE, and then updating the MSDE table with select
columns of info from the Excel spreadsheet. I believe the first set of synt
ax will join the file
with MSDE table, and the second set of syntax will run the import/update. I
f you can assist, please advise. Thank you in advance.|||Dejan, thank you very much for taking the time and offering your assistance.
I apologize in advance for my lack of knowledge in this area, and would li
ke to request further clarification regarding the following:
* my primary objective is to use the ID field in the Excel file and ID field
in the SQL database as the common link between the two sources; once linked
, I simply need to update a currently blank column of names in the SQL datab
ase with the values of name
s from the Excel file -are the SQL commands you provided all that is require
d to completely link and update this column of data
* are all of these commands executed in steps (one after the other) from wit
hin Enterprise Manager
* could you briefly state what each section of your SQL commands actually pe
rforms
* it has been previously suggested that if this may occur on a regular basis
, I should use DTS - is DTS part of Enterprise Manager; is it a standalone p
roduct or does it come as part of MSDE
* does a standalone software product exist which novices can use to perform
these link/updates (ie similar to Adobe GoLive or MS FrontPage generating al
l HTML code for non-programmers)
Thank you again for sharing your advice and expertise.|||> . am I running each section of SQL code from within Enterprise Manager
This is supposed to run in Query Analyzer. You can use the same code in your
application as well.

> . it has been previously suggested that I should be using DTS for these
types of updates -any thoughts
DTS is another possibility, of course.

> . if id# exists in both the Excel file and in the SQL database (and is
used as the common relation) -my only objective is to update a blank column
of names in the SQL database with the values of names from the Excel
file -are all of these steps necessary for this type of simple update
>
For an occasional connection, you could use the Openrowset function as well,
but is is quite complicated to write the correct connection string for the
function.

> I am also a novice when it comes to SQL -could you offer a brief
explaination of the function behind each section of SQL statements.
>
1. sp_addlinkedserver system SP stores connection string as a server alias
in the master.dbo.sysservers table. So you don't have to type the connection
string every time you need the data from Excel.
2. sp_addlinkedsrvlogin szstem SP establishes securitz context for the
linked server. If linked server is Oracle, for example, zou have to login
there. As Excel does not have some special securitz, we use 'false' as the
2nd parameter.
3. sp_tables_ex and sp_columns_ex szstem SP give you info about tables and
columns on the remote source.
4. Select, Create, Insert are standard T-SQL commands.
5. In Excel, you can name a range of cells with a custom name, so you don't
have to refer to them a Sheet1$.
Dejan Sarka, SQL Server MVP
Associate Mentor
Solid Quality Learning
More than just Training
www.SolidQualityLearning.com|||> . I have been told that if I were going to perform this task repeatedly, I
should be using DTS -could you advise (is this part of Enterprise Manager),
or maybe there is another tool you might suggest which simplifies this
link/update procedure for novices (ie Adobe GoLive writes HTML code for
non-programmers)
>
In addition:
DTS is a general tool for transferring the data between OLE DB sourcers. You
can read basic of DTS at
http://msdn.microsoft.com/library/d...r />
71v7.asp.
You can check an advance usage of DTS for transferring the data from Excel
at http://www.sqldts.com/default.aspx?243.
Dejan Sarka, SQL Server MVP
Associate Mentor
Solid Quality Learning
More than just Training
www.SolidQualityLearning.com|||Here is a brief description of my actual data:
Excel File name = inventory.xls
File location = C:\Documents and Settings\POS\Desktop\inventory.xls
Excel current worksheet sample (both columns are 16 character strings):
ITEMNO LOG_SOURCE
A1 13110 B1 White 3 Ring
A2 13111 B2 White 3 Ring
A3 13112 B3 09/09/03
A4 13113 B4 09/09/03
A5 13114 B5 09/09/03
SQL Table Name = ITEMS
SQL current table sample (both columns are 16 character strings):
ITEMNO LOG_SOURCE
13110
13111
13112
13113
13114
The primary objective is to update the LOG_SOURCE column of the SQL database
with the values from the Excel worksheet (using ITEMNO as the link). Pleas
e advise as to the following:
EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Documents and Settings\POS\Desktop\inventory.xls',
NULL,
'Excel 5.0'
* What should I change Excel version name to (using Microsoft Office Excel 2
003)
* could I avoid defining table ranges to save a step or two and simply use c
olumn ranges -in other words, what commands could we eliminate by using Shee
t1 A1:A5 & Sheet1 B1:B5
* Does DTS come as part of MSDE & if so, how do I access it? Would I save a
n time by using DTS rather than your suggested procedure?
* What part of your code triggers the actual update of the SQL server's LOG_
SOURCE column with the Excel values?
Thank you again for your time and expertise.|||Dejan,
Thank you for your reply. Here is a brief description of my actual data:
Excel File name = inventory.xls
File location = C:\Documents and Settings\POS\Desktop\inventory.xls
Excel current worksheet sample (both columns are 16 character strings):
ITEMNO LOG_SOURCE
A1 13110 B1 White 3 Ring
A2 13111 B2 White 3 Ring
A3 13112 B3 09/09/03
A4 13113 B4 09/09/03
A5 13114 B5 09/09/03
SQL Table Name = ITEMS
SQL current table sample (both columns are 16 character strings):
ITEMNO LOG_SOURCE
13110
13111
13112
13113
13114
My primary objective is to update the LOG_SOURCE column of the SQL table wit
h the values from the Excel worksheet (using ITEMNO as the link).
I have to apologize in advance for my limited SQL experience, but here is co
de that I've collected thus far to perform the link:
EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Documents and Settings\POS\Desktop\inventory.xls',
NULL,
'Excel 5.0'
(not sure what I should change Excel version name to if I'm using Microsoft
Office Excel 2003)
EXEC sp_addlinkedsrvlogin 'ExcelSource', 'false'
EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource
SELECT *
FROM ExcelSource...Sheet1$
CREATE TABLE test_excel
(id int,
name varchar(255))
GO
INSERT INTO test_excel
SELECT *
FROM ExcelSource...Sheet1$
SELECT *
FROM test_excel
/* Now define two ranges in Excel on the 2nd sheet as tables */
/* Select the range, Insert->Name->Define */
/* Note: sp_tables_ex does not recognize the defined tables */
/* We can still refer to the tables explicitly */
EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource
SELECT *
FROM ExcelSource...Table1
SELECT *
FROM ExcelSource...Table2
(I wonder if I could avoid defining table ranges to save a step or two and s
imply use column ranges -in other words, what commands could we eliminate by
using Sheet1 A1:A5 & Sheet1 B1:B5 ?)
(what part of your code triggers the actual update of the SQL server's LOG_S
OURCE column with the Excel values?)
Here is the code I've collected thus far to perform the update:
update Items set log_source = t1.log_source
update items
set
items.LOG_SOURCE = t1.LOG_SOURCE
from t1
inner join Items
on items.ItemNo = t1.ItemNo
I'd like to consolidate this code or simplify this process, if possible. Al
so, does DTS come as part of MSDE & if so, how do I access it? Would I save
any time by using DTS rather than your suggested procedure?
Thank you again for your time and expertise.

Joining Excel Database with MSDE Database Table, & Import

Looking for the basic procedure to join an Excel spreadsheet with a table from a database running on MSDE, and then updating the MSDE table with select columns of info from the Excel spreadsheet. I believe the first set of syntax will join the file with MSDE table, and the second set of syntax will run the import/update. If you can assist, please advise. Thank you in advance.Here is the code how to link Excel sheet to SQL Server:
/* Excel as a linked server */
/* Assuming we have an Excel file 'D:\testi\Myexcel.xls'
with following data in the first sheet:
id name
1 a
2 b
3 c
*/
EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'D:\testi\Myexcel.xls',
NULL,
'Excel 5.0'
EXEC sp_addlinkedsrvlogin 'ExcelSource', 'false'
EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource
SELECT *
FROM ExcelSource...Sheet1$
CREATE TABLE test_excel
(id int,
name varchar(255))
GO
INSERT INTO test_excel
SELECT *
FROM ExcelSource...Sheet1$
SELECT *
FROM test_excel
/* Now define two ranges in Excel on the 2nd sheet as tables */
/* Select the range, Insert->Name->Define */
/* Note: sp_tables_ex does not recognize the defined tables */
/* We can still refer to the tables explicitly */
EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource
SELECT *
FROM ExcelSource...Table1
SELECT *
FROM ExcelSource...Table2
-- Dejan Sarka, SQL Server MVPAssociate MentorSolid Quality LearningMore
than just Trainingwww.SolidQualityLearning.com"G. Benson"
<anonymous@.discussions.microsoft.com> wrote in message
news:E7453061-6084-4E62-9759-C06341C28CAC@.microsoft.com...
> Looking for the basic procedure to join an Excel spreadsheet with a table
from a database running on MSDE, and then updating the MSDE table with
select columns of info from the Excel spreadsheet. I believe the first set
of syntax will join the file with MSDE table, and the second set of syntax
will run the import/update. If you can assist, please advise. Thank you in
advance.|||Dejan, thank you for your expertise. So I fully understand your solution, a few questions for you
â?¢ am I running each section of SQL code from within Enterprise Manage
â?¢ it has been previously suggested that I should be using DTS for these types of updates -any thought
â?¢ if id# exists in both the Excel file and in the SQL database (and is used as the common relation) -my only objective is to update a blank column of names in the SQL database with the values of names from the Excel file -are all of these steps necessary for this type of simple updat
I am also a novice when it comes to SQL -could you offer a brief explaination of the function behind each section of SQL statements
Thanks again.|||Dejan, thank you for sharing your expertise. I apologize, but I am a novice in this area and would like to ask for your clarification on the following:
â?¢ my only objective is to use the id field as the link between the Excel file and the SQL database, and simply update a column of blank names in the SQL database to the column of names located in the Excel file -are all of these commands you provided required/complete to accomplish this task
â?¢ would it be possible for you to explain what each section of your SQL commands actually performs
â?¢ are each of these commands executed exclusively in the Enterprise Manager
â?¢ I have been told that if I were going to perform this task repeatedly, I should be using DTS -could you advise (is this part of Enterprise Manager), or maybe there is another tool you might suggest which simplifies this link/update procedure for novices (ie Adobe GoLive writes HTML code for non-programmers)
Thank you again for your time and knowledge.|||Dejan, thank you for sharing your expertise. I apologize, but I am a novice in this area and would like to ask for your clarification on the following
â?¢ my only objective is to use the id field as the link between the Excel file and the SQL database, and simply update a column of blank names in the SQL database to the column of names located in the Excel file -are all of these commands you provided required/complete to accomplish this tas
â?¢ would it be possible for you to explain what each section of your SQL commands actually perform
â?¢ are each of these commands executed exclusively in the Enterprise Manage
â?¢ I have been told that if I were going to perform this task repeatedly, I should be using DTS -could you advise (is this part of Enterprise Manager), or maybe there is another tool you might suggest which simplifies this link/update procedure for novices (ie Adobe GoLive writes HTML code for non-programmers
Thank you again for your time and knowledge
-- G. Benson wrote: --
Looking for the basic procedure to join an Excel spreadsheet with a table from a database running on MSDE, and then updating the MSDE table with select columns of info from the Excel spreadsheet. I believe the first set of syntax will join the file with MSDE table, and the second set of syntax will run the import/update. If you can assist, please advise. Thank you in advance.|||Dejan, thank you very much for taking the time and offering your assistance. I apologize in advance for my lack of knowledge in this area, and would like to request further clarification regarding the following
* my primary objective is to use the ID field in the Excel file and ID field in the SQL database as the common link between the two sources; once linked, I simply need to update a currently blank column of names in the SQL database with the values of names from the Excel file -are the SQL commands you provided all that is required to completely link and update this column of dat
* are all of these commands executed in steps (one after the other) from within Enterprise Manage
* could you briefly state what each section of your SQL commands actually perform
* it has been previously suggested that if this may occur on a regular basis, I should use DTS - is DTS part of Enterprise Manager; is it a standalone product or does it come as part of MSD
* does a standalone software product exist which novices can use to perform these link/updates (ie similar to Adobe GoLive or MS FrontPage generating all HTML code for non-programmers
Thank you again for sharing your advice and expertise.|||> . am I running each section of SQL code from within Enterprise Manager
This is supposed to run in Query Analyzer. You can use the same code in your
application as well.
> . it has been previously suggested that I should be using DTS for these
types of updates -any thoughts
DTS is another possibility, of course.
> . if id# exists in both the Excel file and in the SQL database (and is
used as the common relation) -my only objective is to update a blank column
of names in the SQL database with the values of names from the Excel
file -are all of these steps necessary for this type of simple update
>
For an occasional connection, you could use the Openrowset function as well,
but is is quite complicated to write the correct connection string for the
function.
> I am also a novice when it comes to SQL -could you offer a brief
explaination of the function behind each section of SQL statements.
>
1. sp_addlinkedserver system SP stores connection string as a server alias
in the master.dbo.sysservers table. So you don't have to type the connection
string every time you need the data from Excel.
2. sp_addlinkedsrvlogin szstem SP establishes securitz context for the
linked server. If linked server is Oracle, for example, zou have to login
there. As Excel does not have some special securitz, we use 'false' as the
2nd parameter.
3. sp_tables_ex and sp_columns_ex szstem SP give you info about tables and
columns on the remote source.
4. Select, Create, Insert are standard T-SQL commands.
5. In Excel, you can name a range of cells with a custom name, so you don't
have to refer to them a Sheet1$.
--
Dejan Sarka, SQL Server MVP
Associate Mentor
Solid Quality Learning
More than just Training
www.SolidQualityLearning.com|||> . I have been told that if I were going to perform this task repeatedly, I
should be using DTS -could you advise (is this part of Enterprise Manager),
or maybe there is another tool you might suggest which simplifies this
link/update procedure for novices (ie Adobe GoLive writes HTML code for
non-programmers)
>
In addition:
DTS is a general tool for transferring the data between OLE DB sourcers. You
can read basic of DTS at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dtssql/dts_basic_71v7.asp.
You can check an advance usage of DTS for transferring the data from Excel
at http://www.sqldts.com/default.aspx?243.
--
Dejan Sarka, SQL Server MVP
Associate Mentor
Solid Quality Learning
More than just Training
www.SolidQualityLearning.com|||Here is a brief description of my actual data:
Excel File name = inventory.xls
File location = C:\Documents and Settings\POS\Desktop\inventory.xls
Excel current worksheet sample (both columns are 16 character strings):
ITEMNO LOG_SOURCE
A1 13110 B1 White 3 Ring
A2 13111 B2 White 3 Ring
A3 13112 B3 09/09/03
A4 13113 B4 09/09/03
A5 13114 B5 09/09/03
SQL Table Name = ITEMS
SQL current table sample (both columns are 16 character strings):
ITEMNO LOG_SOURCE
13110
13111
13112
13113
13114
The primary objective is to update the LOG_SOURCE column of the SQL database with the values from the Excel worksheet (using ITEMNO as the link). Please advise as to the following:
EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Documents and Settings\POS\Desktop\inventory.xls',
NULL,
'Excel 5.0'
* What should I change Excel version name to (using Microsoft Office Excel 2003)
* could I avoid defining table ranges to save a step or two and simply use column ranges -in other words, what commands could we eliminate by using Sheet1 A1:A5 & Sheet1 B1:B5
* Does DTS come as part of MSDE & if so, how do I access it? Would I save an time by using DTS rather than your suggested procedure?
* What part of your code triggers the actual update of the SQL server's LOG_SOURCE column with the Excel values?
Thank you again for your time and expertise.|||Dejan
Thank you for your reply. Here is a brief description of my actual data
Excel File name = inventory.xl
File location = C:\Documents and Settings\POS\Desktop\inventory.xl
Excel current worksheet sample (both columns are 16 character strings)
ITEMNO LOG_SOURC
A1 13110 B1 White 3 Rin
A2 13111 B2 White 3 Rin
A3 13112 B3 09/09/0
A4 13113 B4 09/09/0
A5 13114 B5 09/09/0
SQL Table Name = ITEM
SQL current table sample (both columns are 16 character strings)
ITEMNO LOG_SOURC
1311
1311
1311
1311
1311
My primary objective is to update the LOG_SOURCE column of the SQL table with the values from the Excel worksheet (using ITEMNO as the link)
I have to apologize in advance for my limited SQL experience, but here is code that I've collected thus far to perform the link
EXEC sp_addlinkedserver 'ExcelSource'
'Jet 4.0'
'Microsoft.Jet.OLEDB.4.0'
'C:\Documents and Settings\POS\Desktop\inventory.xls'
NULL
'Excel 5.0
(not sure what I should change Excel version name to if I'm using Microsoft Office Excel 2003
EXEC sp_addlinkedsrvlogin 'ExcelSource', 'false
EXEC sp_tables_ex ExcelSourc
EXEC sp_columns_ex ExcelSourc
SELECT
FROM ExcelSource...Sheet1
CREATE TABLE test_exce
(id int
name varchar(255)
G
INSERT INTO test_exce
SELECT
FROM ExcelSource...Sheet1
SELECT
FROM test_exce
/* Now define two ranges in Excel on the 2nd sheet as tables *
/* Select the range, Insert->Name->Define *
/* Note: sp_tables_ex does not recognize the defined tables *
/* We can still refer to the tables explicitly *
EXEC sp_tables_ex ExcelSourc
EXEC sp_columns_ex ExcelSourc
SELECT
FROM ExcelSource...Table
SELECT
FROM ExcelSource...Table
(I wonder if I could avoid defining table ranges to save a step or two and simply use column ranges -in other words, what commands could we eliminate by using Sheet1 A1:A5 & Sheet1 B1:B5 ?
(what part of your code triggers the actual update of the SQL server's LOG_SOURCE column with the Excel values?
Here is the code I've collected thus far to perform the update
update Items set log_source = t1.log_sourc
update item
se
items.LOG_SOURCE = t1.LOG_SOURC
from t
inner join Item
on items.ItemNo = t1.ItemN
I'd like to consolidate this code or simplify this process, if possible. Also, does DTS come as part of MSDE & if so, how do I access it? Would I save any time by using DTS rather than your suggested procedure
Thank you again for your time and expertise.

Joining Excel Database with MSDE Database Table, & Import

Looking for the basic procedure to join an Excel spreadsheet with a table from a database running on MSDE, and then updating the MSDE table with select columns of info from the Excel spreadsheet._ I believe the first set of syntax will join the file with MSDE table, and the second set of syntax will run the import/update._ If you can assist, please advise._ Thank you in advance.You can connect to a csv file (which can be opened in Excel and which an Excel file can be converted into) in good form just as you can to a regular database.

The .csv file needs to be uploaded to the server.

And you can have two recordsets open at the same time.

So I'd suggest going through this recordset one row at a time and within this loop add a new record to the "real" database's recordset.

And for help connecting to a text file using the Jet OLE DB provider:
http://www.able-consulting.com/MDAC/ADO/Connection/OLEDB_Providers.htm#OLEDBProviderForMicrosoftJetTe xt

And based on the above link realize that the actual filename does NOT go in the connection string - rather it goes in the SQL statement (definitely a little tricky).|||Paul,

Thank you for your reply. Here is a brief description of my actual data:

Excel File name = inventory.xls
File location = C:\Documents and Settings\POS\Desktop\inventory.xls
Excel current worksheet sample (both columns are 16 character strings):

ITEMNO LOG_SOURCE
A1 13110 B1 White 3 Ring
A2 13111 B2 White 3 Ring
A3 13112 B3 09/09/03
A4 13113 B4 09/09/03
A5 13114 B5 09/09/03

SQL Table Name = ITEMS
SQL current table sample (both columns are 16 character strings):

ITEMNO LOG_SOURCE
13110
13111
13112
13113
13114

My primary objective is to update the LOG_SOURCE column of the SQL table with the values from the Excel worksheet (using ITEMNO as the link).

I have to apologize in advance for my limited SQL experience, but here is code that I've collected thus far to perform the link:

EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Documents and Settings\POS\Desktop\inventory.xls',
NULL,
'Excel 5.0'

(not sure what I should change Excel version name to if I'm using Microsoft Office Excel 2003)

EXEC sp_addlinkedsrvlogin 'ExcelSource', 'false'

EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource

SELECT *
FROM ExcelSource...Sheet1$

CREATE TABLE test_excel
(id int,
name varchar(255))
GO

INSERT INTO test_excel
SELECT *
FROM ExcelSource...Sheet1$

SELECT *
FROM test_excel

/* Now define two ranges in Excel on the 2nd sheet as tables */
/* Select the range, Insert->Name->Define */
/* Note: sp_tables_ex does not recognize the defined tables */
/* We can still refer to the tables explicitly */

EXEC sp_tables_ex ExcelSource
EXEC sp_columns_ex ExcelSource

SELECT *
FROM ExcelSource...Table1

SELECT *
FROM ExcelSource...Table2

(I wonder if I could avoid defining table ranges to save a step or two and simply use column ranges -in other words, what commands could we eliminate by using Sheet1 A1:A5 & Sheet1 B1:B5)

Here is the code I've collected thus far to perform the update:

update Items set log_source = t1.log_source

update items
set
items.LOG_SOURCE = t1.LOG_SOURCE
from t1
inner join Items
on items.ItemNo = t1.ItemNo

I'd like to consolidate this code or simplify this process, if possible. It has also been suggested that I might use DTS for this type of procedure - does DTS come as part of MSDE & if so, how do I access it?

Thank you again for your time and expertise.

Friday, March 9, 2012

Join with Stored Procedure?

I have a stored procedure A that returns results in this format:

ID
--
1
2
...

I want to make a procedure B that, by joining with the result obtained from A (A INNER JOIN B on A.ID = B.ID), returns a table like this:

ID Title
---
1 Title 1
2 Title 2

But SQL server says invalid object name for A when I try to run B... Assuming stored procedures cannot be "joined", what can I do to obtain similar results?My understanding is that you dont need the first sp. Try this:

Select b.id, b.name where b.id in (select a.id from a)

(Ever tried Select b.id, b.name where b.id in (exec a))

- OR -

Change the type of your first stored procedure to a function that returns table. See help or ask a guru. Then you will (hopefully) be able to do things such as:

select * from a() inner join b on a().id = b.id|||Thanks, using function solved the problem :)

Wednesday, March 7, 2012

join table with procedure?

Is it possible to join the results of a stored procedure with a table?
SELECT field1, field2, field3 FROM tblCustomer INNER JOIN (exec spTest
'inputvar' AS SP) ON tblCustomer.CustID = SP.CustID
Thanks,
KeithKeith G Hicks,
You need to grab the result of the sp into a table (permanent or temporal)
and use the table in the join, or you can re-write the sp as a table functio
n.
create table #t1(c1 ...)
insert into #t1(c1, ...)
exec spTest 'inputvar'
SELECT field1, field2, field3
FROM tblCustomer INNER JOIN #t1 AS SP ON tblCustomer.CustID = SP.CustID
drop table #t1
go
How to share data between stored procedures
http://www.sommarskog.se/share_data.html
AMB
"Keith G Hicks" wrote:

> Is it possible to join the results of a stored procedure with a table?
> SELECT field1, field2, field3 FROM tblCustomer INNER JOIN (exec spTest
> 'inputvar' AS SP) ON tblCustomer.CustID = SP.CustID
> Thanks,
> Keith
>
>|||Cool. That's what I'm doing. I just wasn't sure if there was a way to join
directly to the procedure. Thanks for the info.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:8D7D36E8-8EF7-4E4B-8613-59F8BC64148C@.microsoft.com...
Keith G Hicks,
You need to grab the result of the sp into a table (permanent or temporal)
and use the table in the join, or you can re-write the sp as a table
function.
create table #t1(c1 ...)
insert into #t1(c1, ...)
exec spTest 'inputvar'
SELECT field1, field2, field3
FROM tblCustomer INNER JOIN #t1 AS SP ON tblCustomer.CustID = SP.CustID
drop table #t1
go
How to share data between stored procedures
http://www.sommarskog.se/share_data.html
AMB
"Keith G Hicks" wrote:

> Is it possible to join the results of a stored procedure with a table?
> SELECT field1, field2, field3 FROM tblCustomer INNER JOIN (exec spTest
> 'inputvar' AS SP) ON tblCustomer.CustID = SP.CustID
> Thanks,
> Keith
>
>

join stored procedure and view

Hi everybody
I have this stored procedure called flydate
CREATE PROCEDURE FlyDate AS
declare @.gencalendar table (cal_date datetime primary key)
declare @.p_date datetime
set @.p_date =getdate()

while @.p_date > DateAdd(mm, -3, GetDate()) BEGIN
insert into @.gencalendar(cal_date)
VALUES(@.p_date)

--getdate
SET @.p_date = DateAdd(d, -1, @.p_date)
END

select cal_date AS KF_DATE,0 AS KF_STATUS from @.gencalendar
GO

-which returns all the date for the past three month
and this is my view
CREATE VIEW dbo.rpt_Kids
AS
SELECT TOP 100 PERCENT
KF_ID,dbo.just_date_formal(KF_DATE) as KF_DATE,KF_STATUS FROM dbo.KIDS
order by Year(KF_date) DESC,Month(KF_date) DESC,Day(KF_date) DESC

just_date_formal function
CREATE FUNCTION [dbo].[just_date_formal](@.dtvalue datetime)
RETURNS nvarchar(40)
AS
BEGIN
DECLARE @.display nvarchar(40)
SET @.display = CAST(DATEPART(dd, @.dtvalue) AS nvarchar) + ' ' + CAST(DATEPART(mm, @.dtvalue) AS nvarchar) + ' ' + CAST(DATEPART(yyyy, @.dtvalue) AS nvarchar) + ', ' + CAST(DATENAME(dw, @.dtvalue) AS nvarchar)
RETURN @.display
END

this returns all the date on which error is generated.on other dates on which no error message is generated.
now i want to join both of them so that i get dates of error message and those dates also on which error message is not generated
like

23 june 2005 error
22 june 2005
21 june 2005 error

it should return all dates regardless errror is there or not

Hi,

You directly cannot JOIN the output of a stored procedure in a FROM clause. Stored procedures cannot be used in contexts that require relational expressions. I realize this seems odd at first, since you *can* return a rowset from a stored procedure. However, the reasons we disallow it in TSQL are

(a) The shape of the rowset cannot be determined ahead of time (there is no metadata anywhere that describes the table returned by a stored proc, and besides, the shape returned might depend on the run-time execution path though the proc ... if (condition) select * from somewhere else select * from somewherelese)

and (b) a stored procedure can return > 1 result set.

You have a few options available

1) You can capture the output of the stored procedure into a temporary table using the INSERT INTO EXEC syntax. The code would looks something like:

create table #tempcal(KF_DATE datetime, KF_STATUS int)
go

insert into #tempcal exec FlyDate
go

now you can JOIN on #tempcal.

2) You can refactor your proc to make it into a table-valued function, which you *can* use in a JOIN. You will have to factor-out the non-deterministic getdata() and pass them in as parameters. The code would look something like this

create function FlyDateFunc(@.p_date datetime, @.p_today datetime)
returns @.gencalendar table (KF_DATE datetime primary key, KF_STATUS int)
as
begin
while @.p_date > DateAdd(mm, -3, @.p_today)
begin
insert into @.gencalendar values (@.p_date, 0)
set @.p_date = DateAdd(d, -1, @.p_date)
end

return
end
go

select * from FlyDateFunc(getdate() , getdate())
go

Does this answer your question?
Thanks

|||

Hi,

I have an extra complication to this problem. I have SP's that create dynamic columns based on the parameters they get. So i don't know in advance what my #table should look like. Is there any way to do this without knowing the columns of the #table? (like the select * into #tmp from table1 but then using EXEC? )

I have developed SP's that create dyn columns. Now i want to use these same SP's in SSRS, but that want's to know the column names in advance. So i want to store the results of the SP in a #table and then unpivot that to send it to RS. Think that'll work?

[edit] the SP's use dynamic SQL to get the results

Regards Gert-Jan

join stored procedure and view

Hi everybody
I have this stored procedure called flydate
CREATE PROCEDURE FlyDate AS
declare @.gencalendar table (cal_date datetime primary key)
declare @.p_date datetime
set @.p_date =getdate()

while @.p_date > DateAdd(mm, -3, GetDate()) BEGIN
insert into @.gencalendar(cal_date)
VALUES(@.p_date)

--getdate
SET @.p_date = DateAdd(d, -1, @.p_date)
END

select cal_date AS KF_DATE,0 AS KF_STATUS from @.gencalendar
GO

-which returns all the date for the past three month
and this is my view
CREATE VIEW dbo.rpt_Kids
AS
SELECT TOP 100 PERCENT
KF_ID,dbo.just_date_formal(KF_DATE) as KF_DATE,KF_STATUS FROM dbo.KIDS
order by Year(KF_date) DESC,Month(KF_date) DESC,Day(KF_date) DESC

just_date_formal function
CREATE FUNCTION [dbo].[just_date_formal](@.dtvalue datetime)
RETURNS nvarchar(40)
AS
BEGIN
DECLARE @.display nvarchar(40)
SET @.display = CAST(DATEPART(dd, @.dtvalue) AS nvarchar) + ' ' + CAST(DATEPART(mm, @.dtvalue) AS nvarchar) + ' ' + CAST(DATEPART(yyyy, @.dtvalue) AS nvarchar) + ', ' + CAST(DATENAME(dw, @.dtvalue) AS nvarchar)
RETURN @.display
END

this returns all the date on which error is generated.on other dates on which no error message is generated.
now i want to join both of them so that i get dates of error message and those dates also on which error message is not generated
like

23 june 2005 error
22 june 2005
21 june 2005 error

it should return all dates regardless errror is there or not

Hi,

You directly cannot JOIN the output of a stored procedure in a FROM clause. Stored procedures cannot be used in contexts that require relational expressions. I realize this seems odd at first, since you *can* return a rowset from a stored procedure. However, the reasons we disallow it in TSQL are

(a) The shape of the rowset cannot be determined ahead of time (there is no metadata anywhere that describes the table returned by a stored proc, and besides, the shape returned might depend on the run-time execution path though the proc ... if (condition) select * from somewhere else select * from somewherelese)

and (b) a stored procedure can return > 1 result set.

You have a few options available

1) You can capture the output of the stored procedure into a temporary table using the INSERT INTO EXEC syntax. The code would looks something like:

create table #tempcal(KF_DATE datetime, KF_STATUS int)
go

insert into #tempcal exec FlyDate
go

now you can JOIN on #tempcal.

2) You can refactor your proc to make it into a table-valued function, which you *can* use in a JOIN. You will have to factor-out the non-deterministic getdata() and pass them in as parameters. The code would look something like this

create function FlyDateFunc(@.p_date datetime, @.p_today datetime)
returns @.gencalendar table (KF_DATE datetime primary key, KF_STATUS int)
as
begin

while @.p_date > DateAdd(mm, -3, @.p_today)
begin
insert into @.gencalendar values (@.p_date, 0)
set @.p_date = DateAdd(d, -1, @.p_date)
end

return
end
go

select * from FlyDateFunc(getdate() , getdate())
go

Does this answer your question?
Thanks

|||

Hi,

I have an extra complication to this problem. I have SP's that create dynamic columns based on the parameters they get. So i don't know in advance what my #table should look like. Is there any way to do this without knowing the columns of the #table? (like the select * into #tmp from table1 but then using EXEC? )

I have developed SP's that create dyn columns. Now i want to use these same SP's in SSRS, but that want's to know the column names in advance. So i want to store the results of the SP in a #table and then unpivot that to send it to RS. Think that'll work?

[edit] the SP's use dynamic SQL to get the results

Regards Gert-Jan

Monday, February 20, 2012

JOIN Performace Vs. Multiple RersultSets

Can anyone give me some guidelines as to when to chose JOINS over returning multiple resultsets in a strored procedure..

For eample, I have two tables, Orders and OrderDetails, which are linked by a primary key field. There can be orders w/o a corresponding record in orderdetails.

1.) I can return all orders and their details using a stored preocedure that has:

SELECT o.order_id as OrderId, o.customername, od.order_id, od.orderdate FROM orders AS o LEFT OUTER JOIN orderdetails AS od ON (o.order_id=od.order_id)

2.) I can do the same by returning two results sets in a different stored procedure:

SELECT order_id, customername FROM orders

SELECT order_id, orderdate FROM orderdetails

I think the client processing time for the second option will be slightly less, because the resultset I need to filter will only be as big as the orederdetails table (it will not include records for orders that have no details). Regardless, I think this would only make for a small performance gain, so if Option 1 is better in Database performace, I would probably go with that.

I assume the method to choose also depends on table size and # of JOINS. Any guidance would be appreciated. Thanks,

Al

JOIN is a Cartesian operation INNER JOIN is fastest because technically the tables are equal OUTER JOIN defaults to a mathematical NULL because both tables are not equal and there is fixed table position. UNION is a SET operation it also performs implicit distinct by removing duplicates while UNION ALL leaves the duplicates in. UNION operation is slower than JOIN. So here is the performance list INNER JOIN, OUTER JOIN and UNION. I am assuming you know JOIN uses the FROM and ON clause the WHERE is just a filter like the AND operator. Browse SQL Performance by Peter Gulutzan for more info. Hope this helps.|||Thanks for the reply. The various differences in the performance of different types of JOIN is certainly interesting, but I was hoping to get some info on the relative performance of doing a JOIN versus returning multiple resultsets in a single query or stored procedure. I will look into that book, though.|||

I thought that was what I answered you get multiple result set with the UNION operator and it is slower than any JOIN. Try the link below for ADO.NET 2.0 MARS (multiple active result set) from the SQL Server team. Hope this helps.

http://blogs.msdn.com/sqlprogrammability/archive/2006/05/01/MARSIntroduction1.aspx

|||

I have looked into MARS, and that's not exactly what I am talking about either... I am talking about a single stored procedure which has 2 select statements in it like...

Select * From TableA

Select * From TableB

When you have a .net component which returns a dataset from running this procedure, the dataset will contain 2 tables, so you have access to all the data.

The same can be achieved by returning a dataset with one table in it by using a JOIN. My consern is at what point is the JOIN operation more costly than running the two (or more) separate SELECT statements. My understanding of JOINS is that the db has to scan the entire table (the right hand side of the JOIN) in order to find the corresponding records. Wouldn't this take longer than simply returning all the records from the second table, as is done in multiple resultsets?

|||I don't want to confuse you but JOIN started life with the UNION operator but changed math because it was too slow. Check out the book I told you about earlier Peter said when you see those queries remember to rewrite them with the new syntax. There is a limit to the level for OUTER JOIN ANSI SQL limit is four after that you may get strange results. Hope this helps.|||Thanks for the help|||

Caddre:

... There is a limit to the level for OUTER JOIN ANSI SQL limit is four after that you may get strange results. ....

Hello, Caddre

Do you have references for this statement? Plus any SQL Server implementation? I didn't catch this information from Books Online. Thanks

|||

The reference is in SQL Performance by Peter Gulutzan and you did not see it because Microsoft just implemented ANSI SQL 92 JOIN syntax while Peter the person who gave MySQL stored procs in six months was talking about ANSI SQL 1999 because the current version of ANSI SQL is 2003. ANSI SQL experts will tell you about things vendors like Microsoft will not cover in the docs because although their product works with current ANSI SQL standard they don't want users coming with complains so their docs show older ANSI SQL standard in the docs. Try the link below and read what they covered online for SQL Server 2005, if you write T-SQL and not ANSI SQL it is almost confusing.

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

|||

Strictly speaking, doing 2 selects will return less data, since the join returns data from the parent table multiple times. On the other hand, if you do the join, then you don't have to do a lookup to find the parent order for an order detail. I'd go with the second option because it's easier, and there are other ways to handle memory issues.

In general, it's bad form to suck everything down from a table, unless you know that it's small. Assuming that you get 100 orders/day, in 4 years you'll have 100,000 rows in your orders table. I doubt that you'll need them all in memory very often. With a decent where clause, you can cut that down a lot, improving speed and memory use. (I once had to do some major performance enhancements on a faxing application that someone else wrote. I more than doubled it's speed by replacing a "select * from table" to a query that just got the oldest fax that was eligible to be sent out.)

|||

akashenk,

have you read the article where John Papa has done some tests on

Retrieve all of the data from a single joined query into a single DataTable
Retrieve each rowset (three in all) from a query into its own DataTable using subqueries
Retrieve each rowset (three in all) from a query into its own DataTable using joins
Retrieve each rowset (three in all) from a query into its own DataTable using parameters.

http://msdn.microsoft.com/msdnmag/issues/03/06/DataPoints/

|||Yes, but he's using Northwind, which is a demo database. At the last place I worked, retrieving the Customers database took several minutes. Doing a join took negligably longer than not doing a join. (Several aplications had small middle tier servers just for getting Customer inforation in a timely manner.)|||

This was exactly the sort of info I was looking for. I had a suspicion that doing a join could make for slower performance, but i had no way of knowing for sure.