Showing posts with label tables. Show all posts
Showing posts with label tables. Show all posts

Friday, March 30, 2012

Need to create and access a SQL server database that will reside on an external hard drive

I need to create a SQL server database and add some tables to it. Then access it with a C# application. The problem is that the new SQL server database and it's tables must reside on an external hard drive. How do I point SQL server to this external drive, so that I can create a database on this drive and then create tables and access data on it?

Here are two articles with examples.

http://support.microsoft.com/default.aspx?scid=kb;en-us;q307283&id=kb;en-us;q307283&ln=en-us&rnk=1&sd=msdn&fr=0&qry=q307283&src=dhcs_mspss_msdn_srch&spr=msall

http://www.codeproject.com/cs/database/CreateDB.asp

|||

Hi Steve,

I am interested in setting this up through SQL Server management studio. Your refered links talk about doing it programatically. Neat stuff, but I need to do this through SQL Server management studio. Possibly someone has some more information on this?

|||

You can create a database locally, copy the mdf and ldf files to where you want them, and then attach to the files in the new location. Here is a link in the online help:

ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/6732a431-cdef-4f1e-9262-4ac3b77c275e.htm

Or, right click the server icon and select properties.

Select the Database Settings Page. On that page you can specify what directories you want your data to be in.

|||Once the database and tables have been set up on the external drive, do you know if they can then be viewed and queried through SQL Server Query Analyzer?|||Once the database and tables have been set up on the external drive, do you know if they can then be viewed and queried through SQL Server Management Studio?|||

I tried what I suggested and it didn't work. The Management studio would not let me browse away from the PC it was installed on. I tried hard coding some paths to a remote drive but that didn't work.


Finally, I got this to work (from articlehttp://www.sqlteam.com/item.asp?ItemID=128)

DBCC TRACEON (1807);
GO

USE master;

GO
CREATE DATABASE Test
ON (FILENAME = '\\oak\C\temp\DataBase\SGWTest.mdf'),
(FILENAME = '\\oak\C\temp\DataBase\SGWTest_Log.ldf')
FOR ATTACH;
GO

Once attached, the database will act like any other database. However, I'm beginning to think Microsoft wants the engine and files to be on the same machine. It probably has something to do with performance and reliability :)

|||

Hi Steve. I am just getting back to your post. Thank you for your research and help on this. I am really greatfull to you. You have my vote for a Microsoft MVP! If I knew where to vote, I would vote for you.

I will read the article you suggested. With regards to the above script DBC TRACEON (1807) ...etc. Did you execute this as a SQL stored procedure?

If speed is an issue then I suppose I could always go with an external drive. It appears to me that possibly I can have a seperate instance of SQL server stored on this external drive, and then run that instance off of the external drive. The problem with this though is that I would have to power it up and down. Necessary I suppose if I want to have an external database.

Here is an example of a drive I was thinking about, if I had to go the route of getting an external hard drive.http://www.microcenter.com/byos/byos_single_product_results.phtml?product_id=249658

Talk to you later,

Ralph

sql

Need to copy All oracle tables to SQL Server 2005

I am racking my brain on this one. I am migrating Oracle data to SQL Server and would like an SSIS package that will copy the oracle data from every table to SQL server. I already have the schema set up in SQL and a straight copy of a specified table works fine between the OLEDB source and OLEDB destination. However, when I set up a loop which sets a global variable for the table names, which are identical on both dbs, and try to set the OLEDB Source and Destination OpenRowsetVariable to the global variable, the process fails with these errors with all validation turned off:

[OLE DB Source [18]] Warning: Cannot retrieve the column code page info from the OLE DB provider. If the component supports the "DefaultCodePage" property, the code page from that property will be used. Change the value of the property if the current string code page values are incorrect. If the component does not support the property, the code page from the component's locale ID will be used.

[OLE DB Source [18]] Error: Column "ID" cannot be found at the datasource.

[DTS.Pipeline] Error: component "OLE DB Source" (18) failed the pre-execute phase and returned error code 0xC0202005.

To sum up, I want to set the tables dynamically and have them infer the mappings. The names of the columns are already the exact same on each schema, and the data types are mapped accordingly. I have already verified that the names of the tables have been formatted correctly for each database. If I can't do it this way then how?

You can't change the source at run-time since the Meta-data for the columns is static.

To do a copy like this, you need to have a seperate source and destination for each table. The easiest way to do this is to use the Import/Export wizard in 2005 to generate the package. Select the target database in SSMS, right click it and pick Tasks/Import data to run the wizard. it should be pretty self-explanatory, but, if you have trouble, there is a good section on it in BOL.

|||

swatts777 wrote:

[OLE DB Source [18]] Warning: Cannot retrieve the column code page info from the OLE DB provider. If the component supports the "DefaultCodePage" property, the code page from that property will be used. Change the value of the property if the current string code page values are incorrect. If the component does not support the property, the code page from the component's locale ID will be used.

This warning can easily be fixed by setting AlwaysUseDefaultCodePage=TRUE on the OLE DB Source component.

swatts777 wrote:

To sum up, I want to set the tables dynamically and have them infer the mappings. The names of the columns are already the exact same on each schema, and the data types are mapped accordingly. I have already verified that the names of the tables have been formatted correctly for each database. If I can't do it this way then how?

SSIS won't do this. I'm worried that you might have read some documentation somewhere that led you think that it will. Is that the case?

Like David said, you have to build a data-flow for each table. You could make it easy on yourself and get the import/export wizard to build it for you.

-Jamie

-Jamie

|||

Apparently, my Oracle Provider wasn't registered in SQL, so I did not know I had this option avalable to me. Using Microsoft's OLEDB Provider for Oracle only lets you pull data over using custom queries. I restarted SQL and my oracle provider showed up. WOW! Thanks for all your help, this worked great! I was able to go through each table and map datatypes and everything. Then I saved the whole thing as an SSIS package for use when we go live.

|||

Hi swatts777,

Can you(or anyone else) tell me how to register an Oracle provider as you described above?
i am having the same endless shyte with data types when pulling single values from Oracle.

Anybody please help me

Regards,

Pieter

|||

I think yhe answer is right there...

swatts777 wrote:

I restarted SQL and my oracle provider showed up.

|||

Hi Rafael,

It seems pretty much easy doesn't it, but I'm still not sure if I should have a new version of Oracle installed before I restart my SQL server or install just a driver or what?

Maybe I should change my name to StupidPete?

Regards,

Pieter

|||

Peter,

After installing the Oracle client, you must set up Oracle Net services to point to the correct Oracle database. There are plenty of articles on doing this. You should have installed the Client using Oracle Universal Installer that comes with the client you are using and that you downloaded from Oracle's site. If you have done all of this, then you can restart the machine. That is the best way. If you are using SQL Server 2005, under Server Objects>Linked Servers>Providers you should now see a OraOLEDB.Oracle provider listed. Now you may create your Linked server using this provider instead of MSADORA.

Hope this helps,

Shawn

|||

CleverPete wrote:

Hi Rafael,

It seems pretty much easy doesn't it, but I'm still not sure if I should have a new version of Oracle installed before I restart my SQL server or install just a driver or what?

Maybe I should change my name to StupidPete?

Regards,

Pieter

This is a perfect example of how a flamming thread starts and how they get deleted/locked. I just wanted to point out a detail that you could have miss. BTW, that was quite the answer; just install it and re-start the machine.

Rafael Salas wrote:

I think yhe answer is right there...

swatts777 wrote:

I restarted SQL and my oracle provider showed up.

|||I wasn't really focused on the questions being asked, rather my on experiences in dealing with the problems I faced. I will try to answer questions more precise and pay more attention to the actual questions being posted.|||

I am trying to do the same exact thing, but with a CACHE database, not oracle. My issue is that SSIS will not dynamically map the columns from each new table that I setup in a foreach loop. I do not want to create a separate design time mapping for each table (there are lots of tables). If I cannot figure this out, I will use OPENQUERY with a linked server, and set the OPENQUERY string dynamically in a loop. Unless I misunderstood, you are not dynamically writing to tables with different structures, correct? If so, how did you get that to work?

|||

Dave Dumas wrote:

I am trying to do the same exact thing, but with a CACHE database, not oracle. My issue is that SSIS will not dynamically map the columns from each new table that I setup in a foreach loop.

You're right, it doesn't do this. You can't do what you are attempting unless the columns in all the source tables are the same.

Dave Dumas wrote:

I do not want to create a separate design time mapping for each table (there are lots of tables).

Unfortunately if you want to use data-flows this is your only option.

Dave Dumas wrote:

If I cannot figure this out, I will use OPENQUERY with a linked server, and set the OPENQUERY string dynamically in a loop.

Good idea that. Let us know how it goes.

-Jamie

|||

Thanks Jamie. What I did (since the OPENQUERY syntax does not all variables, only strings), was to write a select statement with dynamic sql as output. I outputted 300 OPENQUERY statements inside of try-catch BEGIN END blocks. This worked great. - Dave

Need to copy All oracle tables to SQL Server 2005

I am racking my brain on this one. I am migrating Oracle data to SQL Server and would like an SSIS package that will copy the oracle data from every table to SQL server. I already have the schema set up in SQL and a straight copy of a specified table works fine between the OLEDB source and OLEDB destination. However, when I set up a loop which sets a global variable for the table names, which are identical on both dbs, and try to set the OLEDB Source and Destination OpenRowsetVariable to the global variable, the process fails with these errors with all validation turned off:

[OLE DB Source [18]] Warning: Cannot retrieve the column code page info from the OLE DB provider. If the component supports the "DefaultCodePage" property, the code page from that property will be used. Change the value of the property if the current string code page values are incorrect. If the component does not support the property, the code page from the component's locale ID will be used.

[OLE DB Source [18]] Error: Column "ID" cannot be found at the datasource.

[DTS.Pipeline] Error: component "OLE DB Source" (18) failed the pre-execute phase and returned error code 0xC0202005.

To sum up, I want to set the tables dynamically and have them infer the mappings. The names of the columns are already the exact same on each schema, and the data types are mapped accordingly. I have already verified that the names of the tables have been formatted correctly for each database. If I can't do it this way then how?

You can't change the source at run-time since the Meta-data for the columns is static.

To do a copy like this, you need to have a seperate source and destination for each table. The easiest way to do this is to use the Import/Export wizard in 2005 to generate the package. Select the target database in SSMS, right click it and pick Tasks/Import data to run the wizard. it should be pretty self-explanatory, but, if you have trouble, there is a good section on it in BOL.

|||

swatts777 wrote:

[OLE DB Source [18]] Warning: Cannot retrieve the column code page info from the OLE DB provider. If the component supports the "DefaultCodePage" property, the code page from that property will be used. Change the value of the property if the current string code page values are incorrect. If the component does not support the property, the code page from the component's locale ID will be used.

This warning can easily be fixed by setting AlwaysUseDefaultCodePage=TRUE on the OLE DB Source component.

swatts777 wrote:

To sum up, I want to set the tables dynamically and have them infer the mappings. The names of the columns are already the exact same on each schema, and the data types are mapped accordingly. I have already verified that the names of the tables have been formatted correctly for each database. If I can't do it this way then how?

SSIS won't do this. I'm worried that you might have read some documentation somewhere that led you think that it will. Is that the case?

Like David said, you have to build a data-flow for each table. You could make it easy on yourself and get the import/export wizard to build it for you.

-Jamie

-Jamie

|||

Apparently, my Oracle Provider wasn't registered in SQL, so I did not know I had this option avalable to me. Using Microsoft's OLEDB Provider for Oracle only lets you pull data over using custom queries. I restarted SQL and my oracle provider showed up. WOW! Thanks for all your help, this worked great! I was able to go through each table and map datatypes and everything. Then I saved the whole thing as an SSIS package for use when we go live.

|||

Hi swatts777,

Can you(or anyone else) tell me how to register an Oracle provider as you described above?
i am having the same endless shyte with data types when pulling single values from Oracle.

Anybody please help me

Regards,

Pieter

|||

I think yhe answer is right there...

swatts777 wrote:

I restarted SQL and my oracle provider showed up.

|||

Hi Rafael,

It seems pretty much easy doesn't it, but I'm still not sure if I should have a new version of Oracle installed before I restart my SQL server or install just a driver or what?

Maybe I should change my name to StupidPete?

Regards,

Pieter

|||

Peter,

After installing the Oracle client, you must set up Oracle Net services to point to the correct Oracle database. There are plenty of articles on doing this. You should have installed the Client using Oracle Universal Installer that comes with the client you are using and that you downloaded from Oracle's site. If you have done all of this, then you can restart the machine. That is the best way. If you are using SQL Server 2005, under Server Objects>Linked Servers>Providers you should now see a OraOLEDB.Oracle provider listed. Now you may create your Linked server using this provider instead of MSADORA.

Hope this helps,

Shawn

|||

CleverPete wrote:

Hi Rafael,

It seems pretty much easy doesn't it, but I'm still not sure if I should have a new version of Oracle installed before I restart my SQL server or install just a driver or what?

Maybe I should change my name to StupidPete?

Regards,

Pieter

This is a perfect example of how a flamming thread starts and how they get deleted/locked. I just wanted to point out a detail that you could have miss. BTW, that was quite the answer; just install it and re-start the machine.

Rafael Salas wrote:

I think yhe answer is right there...

swatts777 wrote:

I restarted SQL and my oracle provider showed up.

|||I wasn't really focused on the questions being asked, rather my on experiences in dealing with the problems I faced. I will try to answer questions more precise and pay more attention to the actual questions being posted.|||

I am trying to do the same exact thing, but with a CACHE database, not oracle. My issue is that SSIS will not dynamically map the columns from each new table that I setup in a foreach loop. I do not want to create a separate design time mapping for each table (there are lots of tables). If I cannot figure this out, I will use OPENQUERY with a linked server, and set the OPENQUERY string dynamically in a loop. Unless I misunderstood, you are not dynamically writing to tables with different structures, correct? If so, how did you get that to work?

|||

Dave Dumas wrote:

I am trying to do the same exact thing, but with a CACHE database, not oracle. My issue is that SSIS will not dynamically map the columns from each new table that I setup in a foreach loop.

You're right, it doesn't do this. You can't do what you are attempting unless the columns in all the source tables are the same.

Dave Dumas wrote:

I do not want to create a separate design time mapping for each table (there are lots of tables).

Unfortunately if you want to use data-flows this is your only option.

Dave Dumas wrote:

If I cannot figure this out, I will use OPENQUERY with a linked server, and set the OPENQUERY string dynamically in a loop.

Good idea that. Let us know how it goes.

-Jamie

|||

Thanks Jamie. What I did (since the OPENQUERY syntax does not all variables, only strings), was to write a select statement with dynamic sql as output. I outputted 300 OPENQUERY statements inside of try-catch BEGIN END blocks. This worked great. - Dave

Need to check a table for errors

Hi - please excuse my newness to this. I have a database with several tables and one of them is causing my application to lag really bad. I figure there is either not enough space or something is just wrong in general and i don't know what. Does SQL Server have a shortcut or easy way to test a table in the database?

Thanks =)If it is only giving performance troubles, I bet it is a large table (either many columns, many rows, or both). Look into the index tuning wizard in Enterprise Manager.|||Originally posted by Avernus
Hi - please excuse my newness to this. I have a database with several tables and one of them is causing my application to lag really bad. I figure there is either not enough space or something is just wrong in general and i don't know what. Does SQL Server have a shortcut or easy way to test a table in the database?

Thanks =)

dbcc checktable(yourtable)?|||Originally posted by snail
dbcc checktable(yourtable)?

Ok will try that.

I also forgot to mention that it has worked fine for a year and all the sudden is causing literally 5 minute lag periods.

Thanks =)|||Originally posted by Avernus
Ok will try that.

I also forgot to mention that it has worked fine for a year and all the sudden is causing literally 5 minute lag periods.

Thanks =)

Also you could check for fragmentation (it is good idea to do this sometimes):

DBCC SHOWCONTIG|||In Query Analyzer execute one of the queries your app issues after setting Show Execution Plan to ON (Ctrl+K.) The corresponding pane will show you how the Optimizer processed the request. Pay close attention to anything in RED there, as well as table/index scans.|||"Also you could check for fragmentation (it is good idea to do this sometimes):

DBCC SHOWCONTIG"

I get an error trying to run this alone. I read something about having to include an Object ID with this command. Can you show me an example of how that looks written out for one table? Thanks, I appreciate this bigtime =)

Wednesday, March 28, 2012

Need to Add Data that is checked on a separate table

Hi all, I hope I can make this understandable. I'm new to SQL and I'm
trying to recreate some tables from an older program. I had to create
new keys, since the old data didn't use keys in the same way and I'm
having problems populating the new keys. I'll give you one abridged
example and see if anyone has any ideas.
The main table is Contracts, with a key of ContractNumber. There is
also a ContractCode. The table is related to DO table by
ContractNumber, but that wasn't used on the old system, so I have to
insert it. ContractCode was, but I can't figure out how to fill in
ContractNumber in DO by comparing the ContractCodes from the two
tables. As I said, I'm new to SQL, and here's the last query I tried,
again to no avail. Any help is appreciated.
INSERT DeliveryOrder (DeliveryOrder_ContractNo)
SELECT Contract_Number
FROM Contracts AS a INNER JOIN DeliveryOrder AS b
ON a.ContractCode = b.DeliveryOrderContractNamehi
you just need to update the DO table DeliveryOrder_ContractNO, So can not
use insert command.
look this ,maybe can get some help
---
create table Contracts(ContractNumber int,ContractCode nvarchar(20))
Create table DeliveryOrder(DeliveryOrder_ContractNO
int,DeliveryOrderContractName nvarchar(20))
insert into Contracts select 1,'CountryA'
union all select 2,'CountryB'
union all select 3,'CountryC'
union all select 4,'CountryD'
insert into DeliveryOrder select NULL,'CountryA'
union all select NULL,'CountryB'
union all select NULL,'CountryC'
union all select NULL,'CountryD'
select * from contracts
select * from DeliveryOrder
contracts table
--
ContractNumber ContractCode
1 CountryA
2 CountryB
3 CountryC
4 CountryD
--
DeliveryOrder table
--
DeliveryOrder_ContractNO DeliveryOrderContractName
NULL CountryA
NULL CountryB
NULL CountryC
NULL CountryD
Update DeliveryOrder set DeliveryOrder_ContractNO=
(
select a.ContractNumber from Contracts a
inner join DeliveryOrder b on b.DeliveryOrderContractName = a.ContractCode
where b.DeliveryOrderContractName = DeliveryOrder.DeliveryOrderContractName
)
select * from DeliveryOrder
drop table contracts
drop table DeliveryOrder
---
DeliveryOrder_ContractNO DeliveryOrderContractName
1 CountryA
2 CountryB
3 CountryC
4 CountryD
"DarkGalahad" wrote:

> Hi all, I hope I can make this understandable. I'm new to SQL and I'm
> trying to recreate some tables from an older program. I had to create
> new keys, since the old data didn't use keys in the same way and I'm
> having problems populating the new keys. I'll give you one abridged
> example and see if anyone has any ideas.
> The main table is Contracts, with a key of ContractNumber. There is
> also a ContractCode. The table is related to DO table by
> ContractNumber, but that wasn't used on the old system, so I have to
> insert it. ContractCode was, but I can't figure out how to fill in
> ContractNumber in DO by comparing the ContractCodes from the two
> tables. As I said, I'm new to SQL, and here's the last query I tried,
> again to no avail. Any help is appreciated.
> INSERT DeliveryOrder (DeliveryOrder_ContractNo)
> SELECT Contract_Number
> FROM Contracts AS a INNER JOIN DeliveryOrder AS b
> ON a.ContractCode = b.DeliveryOrderContractName
>

Need to add a table in merge replication

Hi,
I would like to add a new table in merge replication (200 tables already in
replication).
I followed the steps.
Step 1: In publication properties I included the new table
Step 2: System shows the following messages
One or more tables have already been published. Do you want to update those
articles with the new default?
I gave ‘NO’
Step 3: When I click Apply it shows the following message.
SQL Server Enterprise Manager could not change the properties of article
‘Table name’
Based on object ‘Table name’.
Do you want to continue saving other changes to the publication?
Error 21416: Property ‘destination_owner’ of article ‘Table Name’ cannot be
changed.
Since I have 200 tables in merge replication it asks for 200 times and I
have ‘Yes’ and finally it shows the following error message.
SQL Server Enterprise Manager could not create article ‘NewTablename’ on
object ‘NewTablename’.
Do you want to continue saving other changes to the publication?
Error 20086: Publication ‘DatabaseName’ does not support the nosync type
because it contains a table that does not have a rowguidcol column.
Finally,
I created a new column ‘rowguid’ after that followed the same steps.
Its working fine.
Need clarification:
1.Should I create a similar table in subscriber also? (else it replication
fails)
2.Am I going in a correct way?
Please advise
Thanks,
Soura.
Sometimes the GUI is not your friend. This is one of these cases. I think
what is going on is that this new table is related via DRI to some of the
other tables and the tracking metadata has to be updated. This means a new
snapshot; but for some reason - possibly a bug you are unable to do this
through the GUI.
Your options won't work. Basically you are creating two tables which are
configured somewhat correctly (but not completely) for merge replication,
but are missing the necessary merge replication metadata in the system
tables
What I would do is create a seperate publication. This could be problematic
if you have a lot of subscribers.
Another option which probably is the way to go is to use sp_addmergearticle
like this
sp_addmergearticle 'northwind2','authors','authors',
@.force_invalidate_snapshot=1
This will generate a mini snapshot with just the authors table in it.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"SouRa" <SouRa@.discussions.microsoft.com> wrote in message
news:825361FD-DF36-4D78-9E79-6938A34A9CE2@.microsoft.com...
> Hi,
> I would like to add a new table in merge replication (200 tables already
in
> replication).
> I followed the steps.
> Step 1: In publication properties I included the new table
> Step 2: System shows the following messages
> One or more tables have already been published. Do you want to update
those
> articles with the new default?
> I gave 'NO'
> Step 3: When I click Apply it shows the following message.
> SQL Server Enterprise Manager could not change the properties of article
> 'Table name'
> Based on object 'Table name'.
> Do you want to continue saving other changes to the publication?
> Error 21416: Property 'destination_owner' of article 'Table Name' cannot
be
> changed.
> Since I have 200 tables in merge replication it asks for 200 times and I
> have 'Yes' and finally it shows the following error message.
> SQL Server Enterprise Manager could not create article 'NewTablename' on
> object 'NewTablename'.
> Do you want to continue saving other changes to the publication?
> Error 20086: Publication 'DatabaseName' does not support the nosync type
> because it contains a table that does not have a rowguidcol column.
> Finally,
> I created a new column 'rowguid' after that followed the same steps.
> Its working fine.
> Need clarification:
> 1. Should I create a similar table in subscriber also? (else it
replication
> fails)
> 2. Am I going in a correct way?
> Please advise
> Thanks,
> Soura.
>
|||Actually it seems to generate a completely new snapshot.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"SouRa" <SouRa@.discussions.microsoft.com> wrote in message
news:825361FD-DF36-4D78-9E79-6938A34A9CE2@.microsoft.com...
> Hi,
> I would like to add a new table in merge replication (200 tables already
in
> replication).
> I followed the steps.
> Step 1: In publication properties I included the new table
> Step 2: System shows the following messages
> One or more tables have already been published. Do you want to update
those
> articles with the new default?
> I gave 'NO'
> Step 3: When I click Apply it shows the following message.
> SQL Server Enterprise Manager could not change the properties of article
> 'Table name'
> Based on object 'Table name'.
> Do you want to continue saving other changes to the publication?
> Error 21416: Property 'destination_owner' of article 'Table Name' cannot
be
> changed.
> Since I have 200 tables in merge replication it asks for 200 times and I
> have 'Yes' and finally it shows the following error message.
> SQL Server Enterprise Manager could not create article 'NewTablename' on
> object 'NewTablename'.
> Do you want to continue saving other changes to the publication?
> Error 20086: Publication 'DatabaseName' does not support the nosync type
> because it contains a table that does not have a rowguidcol column.
> Finally,
> I created a new column 'rowguid' after that followed the same steps.
> Its working fine.
> Need clarification:
> 1. Should I create a similar table in subscriber also? (else it
replication
> fails)
> 2. Am I going in a correct way?
> Please advise
> Thanks,
> Soura.
>
sql

Need to access SQL Server 2000 tables

Hello,

I am trying to write a java program that will connect to a SQL Server DB, run some queries, pull some data and try to find some trends in the data.

The problem is that I have a copy of the Database, but I don't have SQL Server. I have been given a backup copy of the database though (SQL Server 2000). I know that in addition to the JDBC driver for SQL Server 2000 I will need something else to be able to access the DB. They have stopped selling SQL Server 2000, also the software tends to be a little expensive.

Is there anything else that I can use that will allow me the functionality of being able to run queries and pull data from the DB using JDBC? Will installing MSDE allow me to do that? Or is there someother software that will allow me to do that? Or do I have no other option except installing SQL Server 2000?

Any help is greatly appreciated.

ThanksHi there,

Will you only be accessing the database for the purposes of reporting (i.e. you won't be changing data and then merging these changes into a master database from which the backup was taken)?

What I would recommend is that you don't use MSDE but you use SQL Server 2005 Express Edition. You can download it here:

Download SQL Server 2005 Express

NB. The download could be quite hefty as you might need to download the .NET Framework 2.0, SQL Server 2005 Express Edition database engine and the Management Studio.

You are able to restore SQL Server 2000 database backups to SQL Server 2005 so what you would do is:

1) Install SQL Server 2005 Express & Management Studio Express (see previous link)

2) Use Management Studio Express to restore the SQL Server 2000 backup (you can do this by creating a new database and then restoring your backup over the top)

3) Download and install the JDBC driver for SQL Server 2005 here:
Download JDBC Driver

4) Write your Java program as required

Well, OK, you don't have to use the JDBC driver as you could also use the JDBC-ODBC bridge which already comes with Java but I'd recommend you use the JDBC driver.

Hope that helps a bit, but sorry if it doesn't

|||Thanks a lot NateV,

I will be using the DB for reporting purposes. I won't be chaning any data on the backend ( no inserts or updates, just selects). I am going to try using SQL Server Express 05 and let you know if it worked.

Thanks Again

Friday, March 23, 2012

need SQL Query Help

I need help with a query,
i have two tables,
name Qty orderID Store
Paper 1000 101 New York
Paper 2000 101 Chicago
Pen 2000 102 New York
Pen 5000 102 Chicago
table two
Purchase
orderID Qty price Date
101 100 $4 7/1/05
101 200 $5 7/15/05
101 360 $3.6 8/5/05
101 150 $5.2 8/30/05
102 400 $6 7/2/05
102 300 $6.5 7/12/05
102 500 $5 8/3/05
for the result, I only want to know the last purchase on each like:
Paper 150 $ 5.2 8/30/05
Pen 500 $ 5. 8/3/05
What should I do in this case? Thanks a lot for your help.
Michael
The following example may get you going. It does not handle time,
change the convert code accordingly.
Since both tables have multiple equivalent orderids, a composite where
will need to be built to ensure uniqueness.
select t1.name, t2.qty, t2.price, t2.date
from table2 t2
inner join table1 t1 on t1.orderid = t2.orderid
where str(t2.orderid) + convert(varchar, t2.date, 112) in
(
select top 1 str(t2.orderid) + convert(varchar, t2.date, 112)
from table2 t2
order by date desc
)
mli wrote:
> I need help with a query,
> i have two tables,
> name Qty orderID Store
> Paper 1000 101 New York
> Paper 2000 101 Chicago
> Pen 2000 102 New York
> Pen 5000 102 Chicago
> table two
> Purchase
> orderID Qty price Date
> 101 100 $4 7/1/05
> 101 200 $5 7/15/05
> 101 360 $3.6 8/5/05
> 101 150 $5.2 8/30/05
> 102 400 $6 7/2/05
> 102 300 $6.5 7/12/05
> 102 500 $5 8/3/05
> for the result, I only want to know the last purchase on each like:
> Paper 150 $ 5.2 8/30/05
> Pen 500 $ 5. 8/3/05
> What should I do in this case? Thanks a lot for your help.
> Michael

need SQL Query Help

I need help with a query,
i have two tables,
name Qty orderID Store
Paper 1000 101 New York
Paper 2000 101 Chicago
Pen 2000 102 New York
Pen 5000 102 Chicago
table two
Purchase
orderID Qty price Date
101 100 $4 7/1/05
101 200 $5 7/15/05
101 360 $3.6 8/5/05
101 150 $5.2 8/30/05
102 400 $6 7/2/05
102 300 $6.5 7/12/05
102 500 $5 8/3/05
for the result, I only want to know the last purchase on each like:
Paper 150 $ 5.2 8/30/05
Pen 500 $ 5. 8/3/05
What should I do in this case? Thanks a lot for your help.
MichaelThe following example may get you going. It does not handle time,
change the convert code accordingly.
Since both tables have multiple equivalent orderids, a composite where
will need to be built to ensure uniqueness.
select t1.name, t2.qty, t2.price, t2.date
from table2 t2
inner join table1 t1 on t1.orderid = t2.orderid
where str(t2.orderid) + convert(varchar, t2.date, 112) in
(
select top 1 str(t2.orderid) + convert(varchar, t2.date, 112)
from table2 t2
order by date desc
)
mli wrote:
> I need help with a query,
> i have two tables,
> name Qty orderID Store
> Paper 1000 101 New York
> Paper 2000 101 Chicago
> Pen 2000 102 New York
> Pen 5000 102 Chicago
> table two
> Purchase
> orderID Qty price Date
> 101 100 $4 7/1/05
> 101 200 $5 7/15/05
> 101 360 $3.6 8/5/05
> 101 150 $5.2 8/30/05
> 102 400 $6 7/2/05
> 102 300 $6.5 7/12/05
> 102 500 $5 8/3/05
> for the result, I only want to know the last purchase on each like:
> Paper 150 $ 5.2 8/30/05
> Pen 500 $ 5. 8/3/05
> What should I do in this case? Thanks a lot for your help.
> Michael

need SQL Query Help

I need help with a query,
i have two tables,
name Qty orderID Store
Paper 1000 101 New York
Paper 2000 101 Chicago
Pen 2000 102 New York
Pen 5000 102 Chicago
table two
Purchase
orderID Qty price Date
101 100 $4 7/1/05
101 200 $5 7/15/05
101 360 $3.6 8/5/05
101 150 $5.2 8/30/05
102 400 $6 7/2/05
102 300 $6.5 7/12/05
102 500 $5 8/3/05
for the result, I only want to know the last purchase on each like:
Paper 150 $ 5.2 8/30/05
Pen 500 $ 5. 8/3/05
What should I do in this case? Thanks a lot for your help.
MichaelThe following example may get you going. It does not handle time,
change the convert code accordingly.
Since both tables have multiple equivalent orderids, a composite where
will need to be built to ensure uniqueness.
select t1.name, t2.qty, t2.price, t2.date
from table2 t2
inner join table1 t1 on t1.orderid = t2.orderid
where str(t2.orderid) + convert(varchar, t2.date, 112) in
(
select top 1 str(t2.orderid) + convert(varchar, t2.date, 112)
from table2 t2
order by date desc
)
mli wrote:
> I need help with a query,
> i have two tables,
> name Qty orderID Store
> Paper 1000 101 New York
> Paper 2000 101 Chicago
> Pen 2000 102 New York
> Pen 5000 102 Chicago
> table two
> Purchase
> orderID Qty price Date
> 101 100 $4 7/1/05
> 101 200 $5 7/15/05
> 101 360 $3.6 8/5/05
> 101 150 $5.2 8/30/05
> 102 400 $6 7/2/05
> 102 300 $6.5 7/12/05
> 102 500 $5 8/3/05
> for the result, I only want to know the last purchase on each like:
> Paper 150 $ 5.2 8/30/05
> Pen 500 $ 5. 8/3/05
> What should I do in this case? Thanks a lot for your help.
> Michael

need sql query

Hi

i have 2 tables
the query that i have written is

select distinct mm.subscriber_id,count(mh.seq_memb_id),mm.PREV_SUB SCRIBER_ID,mm.subscriber_id,mm.DATE_OF_BIRTH,mm.ge nder,decode(mh.elig_status,'Y','YES'),decode(mh.el ig_status,'N','NO')
from hsd_member_master mm,hsd_member_elig_history mh
where mm.seq_memb_id = mh.seq_memb_id
and mm.seq_memb_id in (20621,20622,20623)
group by mm.subscriber_id,mh.seq_memb_id,mm.PREV_SUBSCRIBER _ID,mm.subscriber_id,mm.DATE_OF_BIRTH,mm.gender,mh .elig_status

my result should be
subscriber_id,PREV_SUBSCRIBER_ID,DATE_OF_BIRTH,gen der,no of 'yes' in elig_status,no of 'no' in hsd_member_elig_history.

there is multiple rows for each seq_memb_id in eliDo not use DISTINCT with GROUP BY ;)|||Hi

You are grouping by mh.seq_memb_id but it is not contained in the select clause (except as part of an aggregate function). This looks like a likely candidate for your problem

HTHsql

Need SQL Help

I have following query which is joining couple of tables. i have a field "Status" in MeetingAttendees table. I have to add one more check (probably one more case statement) that if MA.Status=4 then Count(A.AttendeeID) as NoofAttendees. So NoofRSVPs (doesn't matter what is the status in MeetingAttendees table) will return total RSVPs and NoofAttendee will return only # of Attendees. how can i add do that? please help...

SELECT

M.State AS MeetingState,

CASE
WHEN MA.AttendeeType = 1 THEN 'Participant'
WHEN MA.AttendeeType = 2 THEN 'Speaker/Faculty'
WHEN MA.AttendeeType = 3 THEN 'Client'
WHEN MA.AttendeeType = 4 THEN 'Staff'
END AS AttendeeType,

Count(A.AttendeeID) as NoofRSVPs

FROM
Programs P
INNER
JOIN eCDReservations M
ON P.SubCompanyCode = M.SubCompanyCode
AND P.ProgramCode = M.ProgramCode
left outer
JOIN MeetingAttendees MA
ON M.ReservationID = MA.MeetingID
left outer
JOIN Attendees A
ON MA.AttendeeID = A.AttendeeID
left outer
JOIN Regions R
ON MA.RegionCode = R.RegionCode
WHERE
P.SubCompanyCode = @.SubCompanyCode AND
P.ProgramCode = @.ProgramCode




GROUP BY

M.State,

MA.AttendeeType

ORDER BY

MA.AttendeeTypeCOUNT(CASE WHEN MA.Status=4 THEN 'present' END) as NoofAttendees

Wednesday, March 21, 2012

need some help with my sql query

I'm still learning this stuff and I'm a bit confused. I have 3 tables: products, categories and subcategories. the products table has the foreign key for subcategories and the subcategories table has the foreign key for categories. I want to return a table that has the ProductID, SubCategoryID and CategoryID. I can't seem to fiqure out how to get the categoryID to the results table. I'm not sure if I'm supposed to use joins or subqueries to get the categoryID. All I have so far is this:


sql="SELECT Products.ProductID, Products.SubCategoryID FROM Products"

any help would be appreciated.I've come up with the following, i'm not sure if this is the correct way to do it, but it seems to work. I ran it through SQL Query Analyzer and it appears to give the results that i was expecting.


sql="SELECT Products.ProductID, Products.SubCategoryID, (SELECT CategoryID FROM SubCategories WHERE SubCategoryID = Products.SubCategoryID) as CategoryID
FROM Products";

If there is another/better/correct way to do this please let me know. Thanks.|||Another way to do it, which might be more efficient, is:


sql="SELECT Products.ProductID, Products.SubCategoryID, SubCategories.CategoryID FROM Products LEFT OUTER JOIN SubCategories ON Products.SubCategoryID = SubCategories.SubCategoryID";

Terri|||Very good, thanks. That is exactly what I was looking for.

Need some help with design of tables/views

I have an applicaton in which I collect data for different parameters
for a set of devices. The data are entered into a single table, each
set of name, value pairs time-stamped and associated with a device.

The definition of the table is as follows:

CREATE TABLE devicedata
(
device_idintNOT NULL REFERENCES devices(id),-- id in the device
table
datetimedatetimePRIMARY KEY CLUSTERED,-- date created
namenvarchar(256)NOT NULL,-- name of the attribute
valuesql_variantNOT NULL-- value
)

For example, I have 3 devices, and each is monitored for two attributes
-- temperature and pressure. Data for these are gathered at say every
20 minute and every 15 minute intervals.

The table is filled with records over a period of time, and I can
perform a variety of SQL queries.

I have another requirement which requires me to retrieve the *latest*
values of temperature and pressure for each device.

Ideally, I'd like to use the data I have collected to get this
information, and I suppose I can.

What I need is the SELECT statement to do this.
I'd appreciate it very much, if someone can help provide that.
Conceivably, I could use a SQL server View for making this easier for
some of my users.

One alternate technique I thought was to create another table which I
*update* with the latest value, each time I *insert* into the above
table. But it seems like a waste to do so, and introduces needless
referential integrity issues (minor). Maybe for fast access, that is
the best thing to do.

I have requirements to maintain this data for several months/year or
two, so I am dealing with a large number of samples.

Any help would be appreciated.

(I apologize if this post appears twice)Here is the view that you are lookig for.

Please let me know if you require anything else

CREATE VIEW Latest_Data
AS
SELECT device_id, [datetime], name, value
FROM devicedata
INNER JOIN
(
SELECT device_id, max([datetime]) [datetime], name
FROM devicedata
GROUP BY device_id, name
) as DerTab
WHERE
devicedata.device_id = DerTab.device_id AND
devicedata.[datetime] = DerTab.[datetime] AND
devicedata.name = DerTab.name
GO

best Regards,
Chandra
http://groups.msn.com/SQLResource/
http://chanduas.blogspot.com/
------------

*** Sent via Developersdex http://www.developersdex.com ***|||Thanks, I'll try that out.

Another question, performance-wise, is there a near-linear increase in
cost for accessing latest values since the max seems to be computed
each time, or is the cost 'not so bad' since the table is indexed by
datetime?

Thanks again for your help.|||sk (shripathikamath@.hotmail.com) writes:
> Another question, performance-wise, is there a near-linear increase in
> cost for accessing latest values since the max seems to be computed
> each time, or is the cost 'not so bad' since the table is indexed by
> datetime?

Performance-wise a clustered index on (device_id, attribute, datetime)
would be to prefer.

It could also be worth considering of defining the attributes in a
seprate table, and only include the attribute in this table to
hold it down in size, which would also improve performance.

Finally, using [datetime] as the primary key seems funny. What if you
get two values close to each other in time? (Beware that datetime in
SQL Server does only have a resolution of 3.33 milliseconds.)

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks, all that makes sense now. Making datetime the primary key was
sheer thoughtlessness.|||>> Any help would be appreciated. <<

Always a dangerous thing to say; I hope you meant it and were not
fishing for kludges.

This non-relational disaster is called a EAV design and you can Google
the details of why and how it fails. Or just try to write a grouped
query or a simple relational division with your currrent non-table.
The basic problem is that it mixes data and metadata in the table. It
means you never even got to 1NF

What are you using either reserved words or vague words for data
element names? Why did device_id suddenly change its name from table
to table? In an RDBMS, design is at the schema level, not
table-by-table; that is a 1950's file system. Why did you use the
non-relational, proprietary sql_variant data type? Is this make
absolutely sure that this is as non-relational as possible or simply to
destroy portability and all hope of normalization? SQL is a strongly
typed language, not like lower level or OO languages. Try a table
more like this:

CREATE TABLE DeviceReadings
(device_id INTEGER NOT NULL
REFERENCES Devices (device_id),
reading_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
temperature DECIMAL(5,2) DEFAULT 0.00 NOT NULL,
pressure DECIMAL(5,2) DEFAULT 0.00 NOT NULL),
PRIMARY KEY (device_id, reading_timestamp));

I don't know all the attributes, the scales used, reasonable defaults
and all the other basic research you did before you wrote one line of
code. But did you really have something with a NVARCHAR(256) name (I
also see that it can be in Chinese, too)? Something like this leads me
to believe that you jumped on a EAV design because you have no idea
what the problem is or what the data is like at all. The "Fire! Ready!
Aim!" or agile school of data modeling?

>> The data are entered into a single table, ..<<

Perhaps we can name this table the
"Automobiles_and_BritneySpears_and_Squids" table in the data model
since it can hold anything? What is the very definition of a table?
It is a set of things of the same kind entities. If two things are
logically different, they are modeled with different tables that have
the proper attributes.

In an RDBMS, we design at the schema level and not at the table level.
You connect to the entire schema; this is not like the old days when
data from a device was collected on a casette tape drive under RTOS on
DEC equipment in the lab.

>> .. needless referential integrity issues <<

Love that phrase! How would you define a "needful referential
integrity issue"?

>> I have another requirement which requires me to retrieve the *latest* values of temperature and pressure for each device <<

Put this in a VIEW, so it is always current and so that you do not have
to keep updating physical storage. Again, you are still stuck in a
1950's file system mindset.

CREATE VIEW CurrentReadings(device_id, temperature, pressure)
AS
SELECT R1.device_id, R1.temperature, R1.pressure
FROM DeviceReadings AS R1
WHERE reading_timestamp
= (SELECT MAX (reading_timestamp)
FROM DeviceReadings AS R2
WHERE R1.device_id = R2.device_id);

See how easy that is to write with a normalized schema?

Stop over, do it right and get some help if you need it. Also,
remember there are often good reasons to use files to stage and scrub
data.|||--CELKO-- wrote:
> >> Any help would be appreciated. <<
> Always a dangerous thing to say; I hope you meant it and were not
> fishing for kludges.

Yes, I meant it. Particularly since a response to my query does not in
any way behoove me to take it on faith.

> This non-relational disaster is called a EAV design and you can Google
> the details of why and how it fails. Or just try to write a grouped
> query or a simple relational division with your currrent non-table.
> The basic problem is that it mixes data and metadata in the table. It
> means you never even got to 1NF
> What are you using either reserved words or vague words for data
> element names?

It did not matter in the query I was posing, and I have since modified
it to not use reserved words -- they worked fine, but I see the point.
I do not understand your comment on vague words for data element names.

> Why did device_id suddenly change its name from table
> to table?

I am trying to pose a question in a ng as simply as possible, so that I
can get help on a specific question -- that of creating a VIEW. I
should have named it device_id in the referenced table as well --
thanks.

> In an RDBMS, design is at the schema level, not
> table-by-table; that is a 1950's file system. Why did you use the
> non-relational, proprietary sql_variant data type?

I have no requirements to use anything but Microsoft SQL Server 2000
and >. Ever, on this project. So the issue of portability does not
arise. It is however, a very valid point if you point out that
"sql_variant is evil" for other reasons, but portability is not a
concern for me.

Maybe I should have just posed the question in
comp.databases.ms-sqlserver

I have a host of attributes (depending on the device: 23 to 37
currently, no two devices necessarily having the same set) that I need
to collect at varying rates, often, user-specified rates. Often, the
attributes are not collected concurrently -- some are manually entered,
some are collected thru pseudo device drivers, others a combination.

One approach was to have the complete set of variables--the superset,
appear as columns. Strongly typed. That certainly is still under
consideration. However, the nature of the project is such that I need
to accomodate additional devices in the future, and each likely brings
in a different set. I did not know of a solution to handle that.

> Is this make
> absolutely sure that this is as non-relational as possible or simply to
> destroy portability and all hope of normalization?

No, it certainly was not the intent to make it as non-relational as
possible. I do not understand your comment on portability at all. I
only need to use Mirosoft SQL Server 2000 and >.

> SQL is a strongly
> typed language, not like lower level or OO languages.
> Try a table
> more like this:
> CREATE TABLE DeviceReadings
> (device_id INTEGER NOT NULL
> REFERENCES Devices (device_id),
> reading_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
> temperature DECIMAL(5,2) DEFAULT 0.00 NOT NULL,
> pressure DECIMAL(5,2) DEFAULT 0.00 NOT NULL),
> PRIMARY KEY (device_id, reading_timestamp));
> I don't know all the attributes, the scales used, reasonable defaults
> and all the other basic research you did before you wrote one line of
> code.

I could go into that, but that would mean describing my entire project.
I need help with a VIEW which was the reason I posed my question as I
did. The list of variables in my example were temperature and
pressure. In my application, as I mentioned previously, is much larger
(23 to 37 per device, and not necessarily the same set) and collection
is at different rates, some rates 10 to 100 times faster than others.

> But did you really have something with a NVARCHAR(256) name (I
> also see that it can be in Chinese, too)?

Yes, it can be in Simplified Chinese, Japanese, German, and French
(only). The name of the variable is described by the data collection
entity, not up to me.

Is nvarchar not the correct sql type for that?

> Something like this leads me
> to believe that you jumped on a EAV design because you have no idea
> what the problem is or what the data is like at all. The "Fire! Ready!
> Aim!" or agile school of data modeling?

I commend your ability to form this insight from a question on creating
a view.

> >> The data are entered into a single table, ..<<
> Perhaps we can name this table the
> "Automobiles_and_BritneySpears_and_Squids" table in the data model
> since it can hold anything?

We could, but then we would be wrong, since it only holds device data.
Has nothing to do with BritneySpears or Squids, and in this instance
nothing with Automobiles either.

> What is the very definition of a table?

This table holds time series data of a number of attributes (of type
datetime, int, double, bit, and text) of devices.

> It is a set of things of the same kind entities. If two things are
> logically different, they are modeled with different tables that have
> the proper attributes.
> In an RDBMS, we design at the schema level and not at the table level.
> You connect to the entire schema; this is not like the old days when
> data from a device was collected on a casette tape drive under RTOS on
> DEC equipment in the lab.
> >> .. needless referential integrity issues <<
> Love that phrase! How would you define a "needful referential
> integrity issue"?

One that would result from performance considerations when NOT using
normalized forms. For example, in this case, I could have created
another table which would hold only the latest values. That appears to
make additional impositions on referential integrity, which prompted my
question in the first place.

I hold no patents on that phrase, nor do I insist that it is
unambiguous. It is kinda like saying "do the right thing, it is
crucial that you do not do it wrong"

> >> I have another requirement which requires me to retrieve the *latest* values of temperature and pressure for each device <<
> Put this in a VIEW, so it is always current and so that you do not have
> to keep updating physical storage. Again, you are still stuck in a
> 1950's file system mindset.
> CREATE VIEW CurrentReadings(device_id, temperature, pressure)
> AS
> SELECT R1.device_id, R1.temperature, R1.pressure
> FROM DeviceReadings AS R1
> WHERE reading_timestamp
> = (SELECT MAX (reading_timestamp)
> FROM DeviceReadings AS R2
> WHERE R1.device_id = R2.device_id);
> See how easy that is to write with a normalized schema?

Exceptionally easy, even I had it figured out which is probably why I
did not ask that question. Looks a lot like one of the other designs I
am entertaining at the moment. (Yet another is having 23 to 37 tables
representing the attributes, but all that was not relevant when I
asked, what I thought was a simple question)

I appreciate it, thanks for the advice. I'll reconsider if this
approach fits my problem better than the ones discussed here.

Incidentally, in my application, temperature and pressure are not
necessarily recorded at the same time. The above VIEW appears to
return the latest record -- it may or may not correspond to latest
value of the pressure.

If I had to query for "What's the latest value of <one of 23 to 37
attributes> for this device, and when was it last recorded?", the above
may or may not give me the correct result.

Maybe I am missing something.

> Stop over, do it right and get some help if you need it. Also,
> remember there are often good reasons to use files to stage and scrub
> data.

Thanks, that is very helpful.|||sk (shripathikamath@.hotmail.com) writes:
>> In an RDBMS, design is at the schema level, not
>> table-by-table; that is a 1950's file system. Why did you use the
>> non-relational, proprietary sql_variant data type?
> I have no requirements to use anything but Microsoft SQL Server 2000
> and >. Ever, on this project. So the issue of portability does not
> arise. It is however, a very valid point if you point out that
> "sql_variant is evil" for other reasons, but portability is not a
> concern for me.
> Maybe I should have just posed the question in
> comp.databases.ms-sqlserver

Well, you did, but Joe Celko thinks he has a mission to fill here.
No, please don't ask me what that mission would be.

Anyway, from what I could guess from the table description, sql_variant
looks like a good choice to me.

If there are a whole bunch of parameters, and they are dynamcially
added all the time, you cannot have a column for everyone of them.
Instead it's better to have row for each of them. In previous versions
of SQL Server, you would then have a couple of value columns - one for
each data type. sql_variant makes it possible to have a single column.

What is a good thing is to define the attributes somewhere, and with
their definition also keep track of their data type. For an
attributes like temperature, you don't really want to find a
datetime value.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||>> I do not understand your comment on vague words for data element names. <<

Names like "name" beg the question "name of what?" A data element
should tell you what it is at the schema level, without the need for a
local context. The ISO-11179 Standard or my SQL PROGRAMMING STYLE give
some rules for this; it is basically a "<noun><modifier>" pattern --
"client_name", "client_status", etc. where the second part tells the
reader what the scale of the attribute is.

>> I do not understand your comment on portability at all. <<

That is what I said the first ten years I programmed, too :) I have an
essay at DBAzine entitled "I will never port this code" that goes into
the short-sighted attitude of new programmers. One way to assure that
you will not port your code is to write it so poorly or with so many
proprietary extensions that it is cheaper to throw it out and start
over. Wre saw a lot of this with the *= extension when infixed joins
came into SQL Server.

>> other designs I am entertaining at the moment. (Yet another is having 23 to 37 tables representing the attributes, .. Incidentally, in my application, temperature and pressure are not necessarily recorded at the same time.<<

If they are truly independent measurement events, then you need to have
23 to 37 tables with the proper constraints, defaults and keys to model
them. I assumed that several of the measurements are made at the same
time by the same device, rather than by separate devices for each
measurement. Temperature and pressure are a common combination in lab
equipment, various chemical values can be detected with one probe, etc.

sql_variant is a proprietary way to destory First Normal Form and data
integrity. Have you tried to write a CHECK() constraint assure that
this "magical one size fits all" pseudo-column allows the right
datatype and the proper range for all of the 23 to 37 measurement?
That is, what stops me from having a pH reading of "purple", a
temperature of -15 Absolute, etc.

There is an old joke about a teacher quizzing a class of really dumb
kids:

"Billy, what is 3 times 6?"
"ahhhh, Tueday, Teacher!"
"Wrong! Sally, what is 3 times 6?"
"Red!"
"Wrong! James, what is 3 times 6?"
"18!"
"Right! Tell the class how you got the answer."
"I divided Tuesday by red."

That is how I feel about weakly typed data models.|||--CELKO-- wrote:
> >> I do not understand your comment on vague words for data element names. <<
> Names like "name" beg the question "name of what?" A data element
> should tell you what it is at the schema level, without the need for a
> local context. The ISO-11179 Standard or my SQL PROGRAMMING STYLE give
> some rules for this; it is basically a "<noun><modifier>" pattern --
> "client_name", "client_status", etc. where the second part tells the
> reader what the scale of the attribute is.

Thanks, that helps me understand your comment.

> >> I do not understand your comment on portability at all. <<
> That is what I said the first ten years I programmed, too :) I have an
> essay at DBAzine entitled "I will never port this code" that goes into
> the short-sighted attitude of new programmers.

I am not wise enough to presume short-sightedness or the relative
vintage of programmers based on a ng question or two, but have been in
business long enough that I can dare presume if the application/product
*I* am working on will ever require to be ported, and the costs in case
I was wrong.

I do understand that portability is highly desireable, but it is just
another project/application consideration as are costs, market needs,
time-to-market, i18n concerns, development time, testing time, design
and verification time, etc. In my experience, the last three listed,
influence portability more than anything else, and are often severely
underestimated.

That does not automatically translate into portability being an
overarching requirement that trumps all other considerations. If my
customers are strictly Microsoft Windows users, portability to
non-Microsoft solutions is low or more likely, non-existent in terms of
requirements.

In fact, whether I even use a database or not, is of no consequence to
them in *this* application.

Not all applications have the same requirements, which ironically, is
eerily similar to the mantra that is being pummelled: "one size does
not fit all".

> One way to assure that
> you will not port your code is to write it so poorly or with so many
> proprietary extensions that it is cheaper to throw it out and start
> over.

I see your confusion: The requirement is not to assure that the code or
the database will not be ported, instead there is simply no requirement
to port my application to use another database.

> Wre saw a lot of this with the *= extension when infixed joins
> came into SQL Server.
> >> other designs I am entertaining at the moment. (Yet another is having 23 to 37 tables representing the attributes, .. Incidentally, in my application, temperature and pressure are not necessarily recorded at the same time.<<
> If they are truly independent measurement events, then you need to have
> 23 to 37 tables with the proper constraints, defaults and keys to model
> them.

Thanks, I'll devote more time and energies in considering this
approach, further. Any suggested reading on strategies for efficiently
organizing time-series data?

> I assumed that several of the measurements are made at the same
> time by the same device, rather than by separate devices for each
> measurement. Temperature and pressure are a common combination in lab
> equipment, various chemical values can be detected with one probe, etc.
>
> sql_variant is a proprietary way to destory First Normal Form and data
> integrity. Have you tried to write a CHECK() constraint assure that
> this "magical one size fits all" pseudo-column allows the right
> datatype and the proper range for all of the 23 to 37 measurement?
> That is, what stops me from having a pH reading of "purple", a
> temperature of -15 Absolute, etc.

Nothing, at declaration time. (With due respect to Sommarskog's
pointers on this aspect)

And what if I do not need that declarative constraint? In other words,
why I am bound to use that aspect of a RDBMS? What if my application
can live adequately without declarative constraint checks?

One other way I can do this application is to not use a RDBMS at all --
for the purposes of this application, that too is perfectly acceptable.
There is no mandate. One reason I am entertaining MS SQL server is
that I can see value (read time savings) in using SQL to perform the
kind of queries needed in the application. I still need to validate my
design ideas, run it through sufficient benchmarks, etc.

Why does it need to be an all-or-nothing with using an RDBMS? Why
can't I simply log all my raw data into MS SQL server, and then use SQL
for doing some analysis? If I find that constructing SQL queries for
searching data between times with simple filters is adequate for my
application, why would I care if I can write that CONSTRAINT at all?

It is true that I could have bought a nail clipper and a corkscrew
separately, instead of a swiss army knife, but if the swiss army knife
was cheaper, quicker to obtain, and was adequate for my purpose, why
must I be compelled to use the knife instrument in the swiss army knife
at all?

[Insert "use flat files, this application does not need a RDBMS"
soapbox here]

> There is an old joke about a teacher quizzing a class of really dumb
> kids:
> "Billy, what is 3 times 6?"
> "ahhhh, Tueday, Teacher!"
> "Wrong! Sally, what is 3 times 6?"
> "Red!"
> "Wrong! James, what is 3 times 6?"
> "18!"
> "Right! Tell the class how you got the answer."
> "I divided Tuesday by red."
> That is how I feel about weakly typed data models.

:-)

Sommarskog's and Chandra's responses gave me enough pointers on what I
was looking for. So did some of yours. I remain thankful for all
responses.

Since we are indulging in experiences, here's how I feel about some Q&A
on usenet

Question: "What's the time?"

Helpful answer: "3 o'clock"

Helpful answer: "3 o'clock in the afternoon, PST"

Another helpful answer: "3 o'clock in the afternoon, PST. Say, why
don't you buy one of those digital watches, they are on sale at Dell
online!"

An occasional response: "Here's how you build a clock..."

A common response: "If you have to ask for the time in this day and
age, then you are stuck in the 50s, and making dumb mistakes by firstly
asking a stranger for the time. How do you know that his watch is
accurate, or that he even has a watch? How do you know that the
stranger is not lying to you? You'll probably be late for that client
meeting and lose your livelihood if you relied on his answer! I have
seen many friends of mine losing their jobs because they asked
strangers for the time. You rarely ever need to ask the time. You are
better off buying a nice watch -- look at the one I am wearing, for
instance. Be sure that you buy one that will simultaneously show times
in 7 countries in the world. It is important, nay, life-threateningly
important, that the watch does indeed show times in 7 different
countries, because the watch that I used for the first ten years only
kept time in one just time zone, and it is dumb to assume that you'll
never be visiting those 7 countries. And right here in the ISO standard
I am carrying for this watch, it states clearly 'The cost of a watch
showing times in 7 different countries, is nothing, or next to nothing,
provided that you use the watch in the right manner'. Also, do not buy
a digital LCD watch, LCDs were never meant to show time--they are just
an unholy by-product of the moral decay caused by the Nintendo
generation who do nothing but waste time; LCDs were primarily designed
for something else. If an LCD breaks, as it'll in a year or actual
usage, you'll be left with no choice but to replace it. Do the right
thing, and buy an analog watch today -- easy to replace parts if it
breaks. And boy, was I dumb enough in my formative years to actually
believe that just knowing the time in Walla Walla was sufficient!"

Monday, March 19, 2012

Need some advice. Thank You.

Hello,
Today I am creating my first one-to-many relationship database.
My main table is:
USERS
Then I have 4 tables related with this one:
PAYMENTS, ORDERS, BOOKS, ARTICLES
For each user I need to create a field named VALUE.
VALUE = N(PAYMENTS)*4 + N(ORDERS)*2 + N(BOOKS)*10 + N(ARTICLES)*5
N = Number of... / Example: N(PAYMENTS) means "Number of Payments".
My questions are:
1. Should I place the value field in USERS table or create a table named
VALUES and have it connected to USERS table?
2. How can I keep my VALUE field updated for each USER?
Thank You Very Much,
Miguel> 1. Should I place the value field in USERS table or create a table
named
> VALUES and have it connected to USERS table?
None of the above. Don't store calculated values in the database. Put
the calcs in your views, queries and procs.

> 2. How can I keep my VALUE field updated for each USER?
Not a problem if you don't store the value.
If you need more help then the following article explains the best way
to post your problem here:
http://www.aspfaq.com/etiquette.asp?id=5006
David Portas
SQL Server MVP
--|||>> 1. Should I place the value field in USERS table or create a table named
Consider using a view instead. Deriving calculated values are generally
better than having them as persisted data in any base table.
This is not an issue, if a view is used. For details, see the topic on
views, creating a view and if required for any performance reasons, indexed
views, in SQL Server Books Online.
Anith

Need script that can shrink copy of DB to fit on a notebook

I need a script that will take a 40GB 300+ table database and shrink it to the 1st 1000 rows in each table and delete security tables like tblchargecard. Want to get size to about 1gb to fit on a notebook for development. Any suggestions would be appreciated.declare a table variable with two columns, table_name and Table_rowcount.

From a join between sysindexes and sysobjetcs table, get the table names and their respective rowcounts into this table variable.

update the table_rowcount columns with table_rowcount-1000

write a script to automatically generate delete statements for each table, each delete statement being preceded by set rowcount table_rowcount and followed by set rowcount 0 statement.

run this generated script.|||Creative, but I think that will crash if you have relational integrity established, and especially if you are using cascading deletes.

If your database does have cascading deletes, (as it should) then just delete everything but, say, every 10th record, out of the highest level tables in the schema. (You can use something like WHERE Right(PrimaryKey, 1) <> 0 if you have numeric keys, for instance.) Do this in a copy of the database, of course!

As far as "delete security tables like tblchargecard", you'll have to specify those in your script.|||Thanks for the help from both of you. will give this a try.

Monday, March 12, 2012

Need Query Help

Hello Everybody,

I have the following two tables and I need some help crafting the apropriate SQL Query to retrieve the information that I need.

Table: ImageGalleries

GalleryID INT IDENTITY(1,1),
GalleryName VARCHAR(255),
DisplayOrder INT NOT NULL

Table: ImageDetails

ImageId INT IDENTITY(1,1),
GalleryID INT NOT NULL (FKey relationship to above table)
ImageName VARCHAR(255),
DisplayOrder INT NOT NULL

In the ImageGalleries table and ImageDetails table, DisplayOrder is a positive integer value that resents the order on the page in which the respective entries display

Here's my attempted query: I need to pull the ImageGalleries.GalleryID, ImageGalleries.GalleryName, and the corresponding ImageDetails.ImageID for the image with a DisplayOrder of 1 and order the full result set by ImageGalleries.DisplayOrder

I am sure there is a way to form this query but at the moment it is alluding me. I doubt that a lot of people are looking at the message boards on a holiday weekend but just in case I thought I would post this


SELECT
g.GalleryID,
g.GalleryName,
i.ImageId,
i.ImageName
FROM
ImageGalleries g
INNER JOIN ImageDetails i
ON g.GalleryID = i.GalleryID

ORDER BY
g.DisplayOrder,
i.DisplayOrder

one hour turn around time on a holiday season.. I think that's impressive. :)|||1 Hour turn around is indeed impressive on a Holiday. I shall share my condolences that we were both doing work on a Holiday. As far as the query above, thank you for the effort but it didn't quite suit what I was looking for. I just want to return 1 record per image gallery and that of course returns all records in the image gallery. I thought about doing a sub query

select G.GalleryID, G.GalleryName, Q.ImageId, Q.ImageName FROM ImageGalleries LEFT JOIN (SELECT * FROM ImageDetails WHERE DisplayOrder = 1) AS Q ON G.GalleryID = Q.GalleryID ORDER BY G.GalleryID

But instead, I chose to implement the same functionality in a user defined function cuz I never get to use them at my day job.

select *, dbo.GetFirstImage(GalleryID) As ImageName FROM ImageGalleries|||add..


WHERE
q.DisplayOrder = 1

:) oh well.|||Bloody Hell, that was so obvious that I almost want to cry. Thank you. I will go hide my head in shame now.|||naw man. we all make the most obvious mistakes, and they're impossible to find because you never care to look in that direction.

We all hit that wall every other day. don't stress yourself out like that.

Need Query for update and insert in one go.

Hi All,
Please look at the following tables. I have Two tables
Data and TmpData with the following structure.

Data ( All int columns, ID column is Primary and identity)

Id UserID PrgID RoldID
322 1 1 2
323 1 2 2
324 1 3 2
325 2 1 2
326 2 2 2
327 2 3 2
328 3 1 2
329 3 2 2
330 3 3 2

TmpData
Id UserID PrgID RoldID
82 1 1 3
83 1 2 3
84 1 3 3
85 2 1 3
86 2 2 3
87 2 3 3
91 20 1 2
92 20 2 2
93 20 3 2
94 21 1 2
95 21 2 2
96 21 3 2

Now I need to run a query so that
Part 1: It updates existing RoleId columns ( Based on Userid,PrgID) in 'Data' Table with corresponding values from 'Data' table.
Part2 : It inserts new rows in 'TmpData' to 'Data' table.

I am done with Part1 using the simple update statement.

Update Data
Set Data.programroleid=tmp.ProgramRoleID
from TmpData tmp
where Data.userid=tmp.UserId
and Data.programId=tmp.ProgramId

This works fine for existing userids,programids in 'Data' and 'TmpData' tables. But I am struggling with inserting new rows into Data from 'TmpData' ( That exists only in 'tmpData' table). Based on above table structures how do I insert new data into 'Data' table from 'TmpData'.INSERT INTO Data(ID, UserID, PrgID, RoldID)
SELECT * FROM TmpData
WHERE ID not in (SELECT ID FROM TmpData Inner Join Data on TmpData.UserID=Data.UserID and TmpData.ProgID=Data.PrgID and TmpData.RoldID=Data.RoldID)|||ID is auto-generated identity value, and thus cannot be inserted into the target table (unless you specifically disable this for the transaction...).
I wouldn't expect the identity values to match between Data and TmpData anyway, so the "NOT IN" method is probably not appropriate. It is also not efficient. NOT EXISTS is faster than NOT IN.

INSERT INTO Data
(ID,
UserID,
PrgID,
RoldID)
SELECT ID,
UserID,
PrgID,
RoldID
FROM TmpData
WHERE NOT EXISTS
(SELECT *
FROM Data
WHERE Data.UserID = TmpData.UserID
and Data.PrgID = TmpData.PrgID
and Data.RoldID = TmpData.RoldID)

Friday, March 9, 2012

Need Optimal Schedule for Snapshot and Merge Replications

I need to schedule a snapshot replication of some tables and a merge
replication of a couple other tables. I would like to know the best
way to schedule the various replication agents.
My questions are:
- Should I arrange the schedule in this order:
Step 1. Run Snapshot Agent for snapshot replication
Step 2. Run Distribution Agents: one for each branch office
Step 3. Run Snapshot Agent for merge replication
Step 4. Run Merge Agents: one for each branch office
The reason I ask is that I am under the impression that
Distribution Agent has everything to do with snapshot
replication and has nothing to do with merge replication.
Therefore, I may want to run Distribution Agent right
after Snapshot Agent for snapshot replication -- just to
group related tasks together and out of the way.
Is my understanding correct?
What is the correct order anyway?
- I have one Distribution Agent for each branch office.
Likewise, I have one Merge Agent for each branch office.
I have two branch offices; this means I have two
Distribution Agents and two Merge Agents.
Should I start the two Distribution Agents at the same time?
Should I start the two Merge Agents at the same time?
Of course, I could have separate those two Distribution
Agents in two different time slots. But I don't want to do
this in order to avoid keeping track with two different sets
of schedules.
I have a feeling that I should be able to run those two agents
at the same time because the bottleneck is the T1 line between
the central office and each branch office. Is my understanding
correct?
Thanks in advance for any info.
Jay Chan
In general you can run all agents simultaneously if you have a small number of subscribers.
You can leave the distribution and merge agents running continoulsy and they will detect the new snapshot is available for distribution and will distribute it.
Many DBAs like to
1)run their distribution and merge agents in continuous loops
2) or schedule them to restart every 10 minutes or so and have them run continoss
This makes them more resilitent to failure.
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html

Need Opinions on Updating Large tables

I have an incomming table that is similar to the following...
locationNbr, SalesDate, SalesAmt, TranCode, SalesQty
I have to update a table that is formated as such...
locationNbr, historyType, Year, D001, D002, D003, D004... --> D365
I am running a join from the incoming table to the table I need to update to
determine what records I need to Insert.
Then I am using a VB app to create a batch of update statements (because I
couldnt figure out how to dynamically specify columns in T-sql) for those
whose key records already exist.
I would imagine this would run alot faster if I could figure out a way to do
this within an sproc.
Is there a good way that I can dynamically build a SQL Update statement
within an sproc?
And, as I am not extremely familiar with MSSQL, is there any other fast
update methods when you are updating large tables?
Thanks for any input.Jace wrote:
> I have an incomming table that is similar to the following...
> locationNbr, SalesDate, SalesAmt, TranCode, SalesQty
> I have to update a table that is formated as such...
> locationNbr, historyType, Year, D001, D002, D003, D004... --> D365
>
You can use dynamic SQL, but I'm not sure it's going to provide any
improvements over all the processing your going to have to do to move
that nicely normalized table into one that looks strangely denormalized.
What's the story behind the denormalized table? What about leap years?
They have 366 days.
Check out sp_executesql in BOL for more information about how to build
dynamic SQL statements from in T-SQL.
David Gugick
Imceda Software
www.imceda.com|||Well, actually it has 371 columns, but it only uses the last 7 col every 9
years. The reason for the denorm format is for speed in accessing the data
for a forecasting method. This system forecasts 100'000+ skus in several
thousand locations, and I am told that using this table vs a nomalized table
increases the speed a significant amount.
Thanks for your input. And um... What is BOL ? :)
"David Gugick" wrote:

> Jace wrote:
> You can use dynamic SQL, but I'm not sure it's going to provide any
> improvements over all the processing your going to have to do to move
> that nicely normalized table into one that looks strangely denormalized.
> What's the story behind the denormalized table? What about leap years?
> They have 366 days.
> Check out sp_executesql in BOL for more information about how to build
> dynamic SQL statements from in T-SQL.
>
> --
> David Gugick
> Imceda Software
> www.imceda.com
>|||BOL is Books Online - the help documentation that comes with SQL Server.
The denormalized table design is potty and will not scale. Analysis Services
and indexed views are tools designed for this kind of work and can routinely
handle 100s of millions of rows of data.
David Portas
SQL Server MVP
--|||Jace wrote:
> Well, actually it has 371 columns, but it only uses the last 7 col
> every 9 years. The reason for the denorm format is for speed in
> accessing the data for a forecasting method. This system forecasts
> 100'000+ skus in several thousand locations, and I am told that using
> this table vs a nomalized table increases the speed a significant
> amount.
> Thanks for your input. And um... What is BOL ? :)
>
David is right. While denormailzed tables have been used for years in
read-only formats for reporting, it makes sense here to test a properly
designed, nomalized solution before commiting to this one.
David Gugick
Imceda Software
www.imceda.com|||Thanks for the input. Im going to do some testing on this in a denorm table
.
It appears the row count will be around 6.5 billion. Do you think that I
may run into trouble with that many records? Or will I have to split
different history types into different tables?
"David Portas" wrote:

> BOL is Books Online - the help documentation that comes with SQL Server.
> The denormalized table design is potty and will not scale. Analysis Servic
es
> and indexed views are tools designed for this kind of work and can routine
ly
> handle 100s of millions of rows of data.
> --
> David Portas
> SQL Server MVP
> --
>|||You'll almost certainly want to look at Analysis Services and Partitioned
Views for this.
Billions of rows are not uncommon - with the right hardware there is no
problem in principle with tables of that size. You should probably consult o
r
hire someone with AS and VLDB experience though.
David Portas
SQL Server MVP
--