Trouble With Query For Poorly Normalized Db

Aug 21, 2007

I'm working with a database that is poorly normalized and am doing my best to increase the speed of our queries (changing the database itself is not an option right now). Any help with the following situation would be very much appreciated.

There are two tables involved, described below.

DataTable:




Code Snippet

CodeA char(4),
CodeB char(4),
CodeC char(2),
ColA float,
ColB float,
ColC float,
...
ColZ float

NameTable:




Code Snippet

Abbr char(2),
FullName varchar(50)

In the DataTable, the columns named ColA, ColB, ColC, etc., are described in the NameTable where Abbr would be A, B, C, etc., and FullName would be a "nice" text version describing what's stored in that column. For instance, a record in the NameTable might include Abbr = 'A' and FullName = 'Computer Science', and that means that ColA in the DataTable refers to 'ComputerScience'.

The table I'm trying to optimize the creation of in our ASP.NET application needs to have column headings that could be retrieved like this:
SELECT DISTINCT CodeB, CodeC FROM DataTable WHERE CodeA = @CodeA
(Note that CodeC is really just a different representation of CodeB--think 4-digit year vs. 2-digit year--for any given CodeA.)

The row headings for the table could be retrieved like this:
SELECT FullName FROM NameTable

The cells of the table at any given intersection of a row heading and a column heading can be retrieved like this:
SELECT Col? FROM DataTable WHERE CodeA = @CodeA AND CodeB = @CodeB (this selects a single value)
Where the ? of Col? is determined by the Abbr version of FullName shown in the row heading, and @CodeB is determined by CodeB from the column heading.

Right now this table is generated using a lot of loops in the code of the page that require it to query the database for nearly every cell in the table. Even with this poor database design, there has to be a better way than that. I'm hoping there is a way to create a stored procedure that uses temporary tables and joins, or views, or something like that to create the table on the SQL Server and just send the data to the ASP.NET page in a form that can be directly databound to a GridView.

Thanks in advance for any help!

-Mathminded

View 1 Replies


ADVERTISEMENT

Poorly Chosen Query Plan

Oct 12, 2000

I'm running the same query on two computers but getting a different query plan. On one of the servers, the query returns in 10 seconds, on the other server it takes over a minute. What the heck!

1. same hardware configuration on both computers
2. same user databases on both computers
3. same NT setup on both computers
4. same software installed on both computers

I can only imagine that MSSQL7 was setup differently and the query optimizer is making a stupid choice. I've compared numerous SQL server options and they are both the same.

1. sp_configure (same on both computers)
2. properties sheet on each server from enterprise manager (same on both computers)


any ideas???

View 1 Replies View Related

Crosstab Normalized Data To Non-normalized

Oct 26, 2001

I have an allergy table which has a patientid and an allergy id. i would like to create a view(or SQL statement) that will give me a crosstab of a patient and there allergies(like below)

PATID ALLERGY1 ALLERGY2 ALLERGY3 etc
100 MCS DAC004 DAC003
200 MCS DAC004
300 MCS DAC004 DAC003


The patients have from upto 9 allergies(but some may only have one or 2). Is there a way to do this?
Thanks

View 1 Replies View Related

Help W/ Stored Procedure? - Full-text Search: Search Query Of Normalized Data

Mar 29, 2008

 Hi -  I'm short of SQL experience and hacking my way through creating a simple search feature for a personal project. I would be very grateful if anyone could help me out with writing a stored procedure. Problem: I have two tables with three columns indexed for full-text search. So far I have been able to successfully execute the following query returning matching row ids:  dbo.Search_Articles        @searchText varchar(150)        AS    SELECT ArticleID     FROM articles    WHERE CONTAINS(Description, @searchText) OR CONTAINS(Title, @searchText)    UNION    SELECT ArticleID     FROM article_pages    WHERE CONTAINS(Text, @searchText);        RETURN This returns the ArticleID for any articles or article_pages records where there is a text match. I ultimately need the stored procedure to return all columns from the articles table for matches and not just the StoryID. Seems like maybe I should try using some kind of JOIN on the result of the UNION above and the articles table? But I have so far been unable to figure out how to do this as I can't seem to declare a name for the result table of the UNION above. Perhaps there is another more eloquent solution? Thanks! Peter 

View 3 Replies View Related

Moving A Poorly Designed Database To SQL

Sep 27, 2001

I have a Access database which has a address field with multiple data sets in it. I am new to writing code and am having trouble finding a example which will help me split these values out into three seperate fields.

Notice how there is no good order in how they are placed.... Some entry's have commas and some don't. Some have periods and some don't.
EX:
[BILL_ADDR3]
AMHERST, WI. 54406
ASHLAND, WI 54806
ASKOV MN 55704

I then need to convert the state to a state code ie:

2 AK
3 AL
4 AR
5 CA
6 CO
7 CT
8 DC
9 DE
10 FL
11 GA
12 HI
13 IA
14 ID
15 IL
16 IN
17 KS
18 KY


Any good sources of information would be greatly appreciated..... Thank You

View 1 Replies View Related

Working With A Poorly Documented SQL Database.

Feb 6, 2008

One of the primary parts of my job is working with the SQL database of our Enterprise ERP software. One of my primary responsibilities is writing reports based on it's data and since it is not well documented and this is one of my biggest challenges. To top it all off, it's hard to even use their reports to learn the links between tables as the reports run completely in Visual Foxpro.

Is there reasonably priced software that will analyze the database for me and make it easier for me to figure out the relationships between certain tables and such?

TIA,

Dave

View 1 Replies View Related

Transaction Log Full Due To Poorly Configured SQL Database

Dec 23, 2005

Good evening all,

I am new to Microsoft SQL and have been dumped right into the deep end with an anchor around my ankles.

The problem I am experiencing is about 6 months back a guy setup a Microsoft SQL server at my client. He then took his bags and left. Then a developer developed an application which uses a database on this sql server. Everything worked well for around 4 months.

Yesterday IBM Director notified me that I am running dangerously low on disk space on the server. By the time I came in to work this morning I had 12mb free disk space. The evil thing here is the transaction log for the downtime database. It has grown to over 60gb, all because the correct measures were not implemented to prevent this.

The problem that is occuring is no one can do anything on the database now due to the lack of free space. I have tried reading the sql books online but due to my lack of sql experience and knowledge I am stuck.

Can someone please help me? What I would like to do is pull my transaction log down to an acceptable size.

I was thinking of creating a new database and then importing all the data from the current database and then just deleting the current database however am slightly concerned that this may result in some data being lost.

Thanks in advance,

Richard

View 9 Replies View Related

Having Trouble With LIKE In Query

Mar 2, 2007

I have a table adapter query with a like clause that I can't get to work.  The field is "Type", so I have "LIKE '%@Type%'".  When I click the Execute Query button to test, not only does nothing get returned, I don't get the chance to enter the parameter.  If I change LIKE '%@Type%' to say, LIKE '%book%', the appropriate records are returned.  I actually need to check two parameters.  If I ad the second parameter, the where clause becomes(Type LIKE '%@Type%') AND (SendState = @SendState)When I test the query, a screen pops up to let me enter the state, but not the Type.  I can't see anything wrong with the query, but something must be. Diane 

View 4 Replies View Related

Trouble With Sub Query

Jun 10, 2008

I am having some trouble using a sub query. I want to use the red part as a sub query because I have to alter some values based on the NcodeM that gets assigned to each record. As a stand alone query the red part works well. When I run the whole thing I get error message:

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near ')'.



Select SaleYear, SaleMonth, vin10, NewUsed, VehicleYear,
VehicleMake, VehicleModel, VehicleTrim, AlgCode, CashDown, AppZip, ActualSalePrice,
TradeMake, TradeModel,TradeYear, TradeNcodeL, TradeNcodeM, OwingOnTrade, TradeAllowance, NetTradeIn

From D

(select left(consulting.dbo.vw_dds.date,4) AS SaleYear, left((right(consulting.dbo.vw_dds.date,4)),2)
AS SaleMonth,
vin10, NewUsed, VehicleYear, VehicleMake, VehicleModel, VehicleTrim, AlgCode, CashDown,

AppZip, (CashPrice-Rebate-TaxesIncludedInCashPrice) AS ActualSalePrice,

ltrim(consulting.dbo.vw_dds.trademake) AS TradeMake, ltrim(trademodel)TradeModel,
TradeYear, NcodeL AS TradeNcodeL, NcodeM AS TradeNcodeM, OwingOnTrade, TradeAllowance, NetTradeIn

from consulting.dbo.vw_dds

inner join (select distinct make, model, ncodel, ncodem, modelyear from us.dbo.algmaster) Code

on code.make = ltrim(consulting.dbo.vw_dds.trademake) and code.model= ltrim(trademodel) and
code.modelyear = tradeyear) D

Any suggestions would be greatly appreciated.

Thanks,
Tasha

View 2 Replies View Related

Query Trouble

Nov 8, 2007



I am having trouble figuring this one out.

I have a table named studentgrades

In it, it contains studentid, teacherid, classgrade


If I do this code it gives me the count of student that made an "A" grouped by teacherid

select
teacherid,
count(grade) as GradeACount
where
classgrade between 90 and 100
from
studentgrades
group by
teacherid

ok this seems simple enough...if I manilpulate the where clause I can get "B","C" and "D" student counts.

My question is how can i get a dataset to return

teacherid,GradeACount,GradeBCount,GradeCCount,GradeDCount

all in one query...I am trying to automate a report so that school districts can pull their own queries via Reporting Services.


I appreciate your time.

Alex Flores

View 5 Replies View Related

Convoluted Query Trouble

Nov 16, 2006

Our Client/Contact database works like this:

CLIENTDB - This table holds the records of all Clients, Contacts, Suppliers, etc. They are defined as one type of record or another by the 'Contact_Type' field - Clients are type 'B', Contacts are 'D', etc.

Contacts are often linked to a Client, but don't have to be. These links are stored in the LINKS table.

So, what I'm trying to do, is generate a report of all Contacts that aren't linked to Clients but possibly should be because they share a company name. The SQL I've used to get this info is as follows:

SELECT *, CLIENTDB.Formal_Name as FN
FROM CLIENTDB
WHERE (CLIENTDB.Contact_Type = 'D')
AND (NOT EXISTS (SELECT * FROM CLIENTDB, LINKS JOIN CLIENTDB as CB ON CLIENTDB.Contact_ID = LINKS.Link_Record_ID))
AND (EXISTS (SELECT * FROM CLIENTDB WHERE (CLIENTDB.Contact_Type = 'B') AND (lower(CLIENTDB.Formal_Name) LIKE '$FN')))


The problem is the final AND condition - I want this to filter the results down to only those Contacts that have a Formal_Name like an existing Client, but when I add or remove this one line, it makes no difference to the output.

Any suggestions greatly appreciated

Thanks, Nick

View 1 Replies View Related

Having Trouble With A Difference Query

May 28, 2008

Hi, I have created a query (using SQL 2005) that will pull the people who have spent the most on tickets purchased:

Select P.Passenger_ID, Passenger_Name, Ticket_Price
From Passenger P, Ticket_Purchase T
Where P.Passenger_ID = T.Passenger_ID
Group By P.Passenger_ID, Passenger_Name, Ticket_Price
Having Ticket_Price >= All (Select Max(Ticket_Price)
From Ticket_Purchase
Group By Ticket_Price);


Passenger_ID Passenger_Name Ticket_Price
---------------------------------------
132812298 Nice,Richard 1750.00
234890032 Franco,Sylvia 1750.00
339209841 Kim,Jongouk 1750.00
385894857 Uribe,Gloria 1750.00

(4 row(s) affected)


I now want to be able to only choose the Passenger_ID's from above who are not listed in another table called Frequent_Flier, which should leave me with only 2 records not 4.


I am wondering if I add the below to the first query to eliminate those passengers in the Frequent_Flier table:
NOT IN (Select Passenger_ID
From Frequent_Flier);

When I add it to the Where clause I get an error. Should I be sub-querying that differently or is there a better way to do this.

Thanks for any help you can offer.

View 4 Replies View Related

Trouble With SQL Query Problem

Nov 13, 2006

Employee
EMPLOYEE_IDLAST_NAMEFIRST_NAMEMIJOB_ID MANAGER_IDHIRE_DATESALARYCOMMISIONDEPARTMENT_ID PHONE_NUMBER

Job
JOB_IDFUNCTION JOB_TYPE
Department
DEPARTMENT_IDNAMELOCATION_ID
Location
LOCATION_IDREGIONAL_GROUP
Here are the different tables in my database and Im trying to get a list of all the managers last names with the last names of the people that the manager manages. FUNCTION describes who is a manager and who has other positions. You can link the two tables together with Job_ID.

Im stuck on this, Im a noob at SQL. Please help

View 2 Replies View Related

Trouble With Update Query

Feb 3, 2008



I want to fill in a field whose name is stored in a variable. This code runs, but the field is not filled in afterward. I think I'm doing something wrong:


SET @field = N'bindery'

SET @ordernum = N'SM38948M08'


UPDATE Orders

SET @field = GETDATE() + 5

WHERE ordernum = @ordernum


My problem is related to using the @field variable in the UPDATE query.

How do I fix this?

Thanks!
Brian

View 8 Replies View Related

Trouble Using Group By Statement With Query

Mar 20, 2007

Hi,
I am having trouble getting my query right. i am using a stored procedure to retrieve this data and bind it to my grid view.
Problem: I can't associate a field with a column that i am returning with my record set.
Details: I have query that i want to return 9 columns (UserName, Pre-Approved, Processing, Underwriting, Conditioned, Approved, Docs Out, Docs Back, Conditions Met). The username column lists all loan agents. I want the other 8 columns to list the name of the borrower (crestline..borrower.lastname)  that is associate with that loan agent and that loan state.  Each time a record is found where there is a valid loan agent (UserName) that meets the 'where' conditions, there will be a borrower. the 'LoanKey' field is a primary key that lets me get the borrower name from the borrower table. I dont know how to construct my query such that those borrower names get associated with their respective column header.
if the query works, my Gridview should look like this ('Name' refers to the borrower name)
UserName | Pre-Approved | Processing | UnderWriting | Conditioned | Approved | Docs Out | Docs Back | Conditions Met 
Bob           |                     |                  |                     |    Name      |                |               |                   |
Bob           |                     |      Name   |                     |                   |                |               |                   |      
Bob           |                     |                  |                     |                   |                |               |      Name    |        
Steve         |                     |                  |      Name      |                   |                |               |                   | 
Steve         |                     |                  |                     |                   |                |    Name  |                   |
 
Here is my sql call: 
SELECT cfcdb..users.username, crestline..borrower.lastname,CASE WHEN crestline..loansp.LoanStatus='Pre-Approved' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Pre-Approved',CASE WHEN crestline..loansp.LoanStatus='Processing' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Processing',CASE WHEN crestline..loansp.LoanStatus='Underwriting' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Underwriting',CASE WHEN crestline..loansp.LoanStatus='Conditioned' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Conditioned',CASE WHEN crestline..loansp.LoanStatus='Approved' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Approved',CASE WHEN crestline..loansp.LoanStatus='Docs Out' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Docs Out',CASE WHEN crestline..loansp.LoanStatus='Docs Back' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Docs Back',CASE WHEN crestline..loansp.LoanStatus='Conditions Met' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Conditions Met'FROM cfcdb..usersinner join (crestline..loansp inner join crestline..borrower on crestline..loansp.loankey = crestline..borrower.loankey)on crestline..loansp.fstnamelo=cfcdb..users.firstname AND crestline..loansp.lstnamelo=cfcdb..users.lastnameinner join cfcdb..users_roleson cfcdb..users.username = cfcdb..users_roles.usernamewhere cfcdb..users.active = 1 AND cfcdb..users_roles.groupid = 'agent'AND crestline..loansp.enloanstat <> 'Closed' AND crestline..loansp.enloanstat <> 'Cancelled' AND crestline..loansp.enloanstat <> 'Declined' AND crestline..loansp.enloanstat <> 'On Hold'order by cfcdb..users.username asc
 

View 2 Replies View Related

Query Trouble Regarding Bitwise Exclusive

Feb 25, 2001

HI, i am trying to make query that has computations with it. but when there's a point computing between int and float i had to use cast() function to convert certain data types. somehow it only works on converting float to integer because when i'm converting an integer into float inorder to be computed with a float it bombs. my query is like this ....


SELECT cast(((cast(((lat - (SELECT LAT FROM TPS_ZIPUSA WHERE ZIP_CODE = 00210)) * 69.1) AS int) ^ 2) + (cast((69.1 * (lng - (SELECT Lng FROM TPS_ZIPUSA WHERE ZIP_CODE = 00210)) * (COS((SELECT LAT FROM TPS_ZIPUSA WHERE ZIP_CODE = 00210) / 57.3))) AS int) ^ 2)) AS float) ^ .5
FROM TPS_ZIPUSA


.5 is where the query bombs. any idea why is this happenning?

by the way, i'm using sql server 7.0.

francis,

View 2 Replies View Related

Select Query Union Trouble

Nov 26, 2007

Given the following tables:

[Members]
-memberID (PK)
-memberName

[Questions]
-questionID (PK)
-questionText

[Surveys]
-surveyID (PK)
-surveyName
-surveyDescription
-surveyType (FK)

[SurveyQuestions]
-surveyID (PK/FK)
-questionID (PK/FK)

[SurveyQuestionMemberResponse]
-surveyID (PK/FK)
-memberID (PK/FK)
-questionID (PK/FK)
-yesResponse(bit)
-noResponse(bit)
-undecidedResponse(bit)

How can I write a query to return the results for a given survey for all members (including members who have not given responses) given the surveyID.

In the [SurveyQuestionMemberReponse] table I record survey results for any members who have answered the survey. However, if a member has not responsed to the survey they will not have a record in this table.

I want to return a list of members with their response to each question in the survey. If a member has not given a response I would like to indicate they have not responded to the survey and they should still appear in the list.

When I attempt to write a query to UNION the results of a query aimed at gathering all of the results in the [SurveyQuestionMemberReponse] to all of the people in the [Members] table I recieve an error when I include the questionText field in my result set.

The error indicates:

The text data type cannot be selected as DISTINCT because it is not comparable.

Can someone please point me in the right direction. I suspect I am going about this all wrong.

[NOTE] The 'surveyType' in the [Surveys] table indicates which subset of members a given Survey should be available to. For this example let's just assume that every survey should belong to all members.

Thanks,

Zoop

View 3 Replies View Related

Trouble Translating Query From Access To SQL Server

Feb 16, 2006

Gary writes "I'm imported the query from Access (where it worked perfectly) to SQL View where the "Iif" statements caused an issue.

Here's a SMALL portion of the original:
SELECT tblTransactionBuyer.TransBuyerID,
tblDefaults.CompID,
([TransBuyerPropSalePrice]*([DefBasePercentVA])/100) AS LoanBaseVA,
[TransBuyerPropSalePrice]*
(IIf([TransBuyerPropSalePrice]>=[DefLoanMinJumbo],[DefFundingJumboVA],
IIf([TransBuyerVaUsed]="Yes",[DefFundingUsedVA],[DefFundingVA])))/100 AS VAFunding, ......


Below, are my changes so far, but I'm stuck.
SELECT tblTransactionBuyer.TransBuyerID,
tblDefaults.CompID,
([TransBuyerPropSalePrice]*([DefBasePercentVA])/100) AS LoanBaseVA,

[TransBuyerPropSalePrice]*
If([TransBuyerPropSalePrice]>=[DefLoanMinJumbo],[DefFundingJumboVA],
If([TransBuyerVaUsed]="Yes",[DefFundingUsedVA],[DefFundingVA]/100)) AS VAFunding, ........

It appears that I may not be able to put an IF into a SQL SELECT. If not, how can I get the same effect ?

Thanks. Gary

Listed Below is the Full Access Query:

SELECT tblTransactionBuyer.TransBuyerID, tblDefaults.CompID, tblTransactionBuyer.TransBuyerEntryDate, qryUserAlphaList.UserName, qryUserAlphaList.UserAreaCode, qryUserAlphaList.UserPhone, tblTransactionBuyer.TransBuyerName, tblTransactionBuyer.TransBuyerVaEligible, tblTransactionBuyer.TransBuyerPropAddress, tblTransactionBuyer.TransBuyerPropCity, tblTransactionBuyer.TransBuyerPropSalePrice, ([TransBuyerPropSalePrice]*([DefBasePercentFHA])/100) AS LoanBaseFHA, ([TransBuyerPropSalePrice]*([DefBasePercentCONV])/100) AS LoanBaseCONV, ([TransBuyerPropSalePrice]*([DefBasePercentVA])/100) AS LoanBaseVA, ([TransBuyerPropSalePrice]*([DefBasePercentJumbo])/100) AS LoanBaseJumbo, [LoanBaseFHA]*[DefMipFHA]/100 AS MipFHA, [LoanBaseCONV]*[DefMipCONV]/100 AS MipCONV, [LoanBaseJumbo]*[DefMipJumbo]/100 AS MipJumbo, [TransBuyerPropSalePrice]*(IIf([TransBuyerPropSalePrice]>=[DefLoanMinJumbo],[DefFundingJumboVA],IIf([TransBuyerVaUsed]="Yes",[DefFundingUsedVA],[DefFundingVA])))/100 AS VAFunding, [LoanBaseFHA]-[DownOverMinFHA]+[MipFHA] AS LoanTotalFHA, [LoanBaseCONV]-[DownOverMinCONV]+[MipCONV] AS LoanTotalCONV, [LoanBaseJumbo]+[MipJumbo]-[DownPaymentJumbo] AS LoanTotalJumbo, [LoanBaseVA]+[VAFunding]-[DownPaymentVA] AS LoanTotalVA, [TransBuyerPropSalePrice]*([DefMinDownPayFHA]/100) AS MinDownFHA, [TransBuyerPropSalePrice]*[DefMinDownPayCONV]/100 AS MinDownCONV, [TransBuyerPropSalePrice]*[DefMinDownPayVA]/100 AS MinDownVA, [TransBuyerPropSalePrice]*[DefMinDownPayJumbo]/100 AS MinDownJumbo, tblTransactionBuyer.TransBuyerIntRate, tblTransactionBuyer.TransBuyerLoanYears, tblTransactionBuyer.TransBuyerHazardIns, tblTransactionBuyer.TransBuyerFloodIns, tblTransactionBuyer.TransBuyerClosingDate, IIf(([TransBuyerConvDownPayPercent]/100)*[TransBuyerPropSalePrice]>[TransBuyerConvDownPayCash],([TransBuyerConvDownPayPercent]/100)*[TransBuyerPropSalePrice],[TransBuyerConvDownPayCash]) AS ConvDownPay, tblDefaults.DefBuyAppraisal, tblDefaults.DefBuyCreditReport, tblDefaults.DefBuyJumboUnderwriting, tblDefaults.DefBuyVAUnderwriting, tblDefaults.DefBuyFHAUnderwriting, tblDefaults.DefBuyCONVUnderwriting, tblDefaults.DefBuyJumboTaxService, tblDefaults.DefBuyVATaxService, tblDefaults.DefBuyFHATaxService, tblDefaults.DefBuyCONVTaxService, tblDefaults.DefBuyFloodCert, tblDefaults.DefBuyAbstractTitle, tblDefaults.DefBuyMiscFedex, tblDefaults.DefBuyRecording, tblDefaults.DefBuySurvey, tblDefaults.DefBuyAttorney, tblDefaults.DefBasePercentFHA, tblDefaults.DefBasePercentCONV, tblDefaults.DefBasePercentJumbo, tblDefaults.DefBasePercentVA, [TransBuyerPropSalePrice]*[DefPropTaxRate] AS PropTax, [LoanBaseFHA]*[DefBuyOrigFHA]/100 AS OrigFHA, [LoanBaseCONV]*[DefBuyOrigCONV]/100 AS OrigCONV, [LoanBaseVA]*[DefBuyOrigVA]/100 AS OrigVA, [LoanBaseJumbo]*[DefBuyOrigJumbo]/100 AS OrigJumbo, [DefTitleInsDollar]*([TransBuyerPropSalePrice]/[DefTitleInsPerX]) AS TitleInsurance, [OrigFHA]+[DefBuyAppraisal

View 1 Replies View Related

Using A Normalized (vertical) Table

Sep 24, 2007

I'm working on a couple projects and I've recently been trying to make everything fully normalized so updates are easier and I'm just wondering if there's a standard way to query and update normalized tables.
For example:
If I have table People with columns ID, FirstName, LastName, Height, Weight, ShoeSize, I can normalize that into two tables. Table People has ID, FirstName and LastName. Table PeopleDetails has PeopleID (FK), Property and Value. That way i can add more properties later right at the presentation layer if I like. Essentially I moved the data from being horizontal to being vertical.
But doing a simple search for people means I have to search the details table and return a LOT more records (one each for Height, Weight and ShoeSize) not to mention any more details I might add later. With a lot of details, it seems like your performance would take a big hit and your code would get really complicated as your looping through a vertical dataset to find the properties you want. Or is there some other standard way of doing that?
I'm just hoping that someone else has solved these problems and there's a standard set of functions out there for selecting and updating this kind of DB structure. Anyone?

View 6 Replies View Related

Creating A Normalized Database

Apr 12, 2007

Hi. I have a project I need to complete and I really don't know the first step I should take. Basically, we have a case management system that is normalized for the most part except for one major flaw: the clients table. Whenever we add a new case, we have to add the customer's name/address/phone etc. all over again. I would like to redo this current setup so we have one table just for clients and another table just for cases, so we don't have all this double entering all the time. Is there an easy way to do this or could someone point me in the right direction? It's on a SQL Server 2000 database. Thanks for your help!

View 6 Replies View Related

How To Check Normalized Tables?

May 7, 2004

Hello, everyone:

Some tables werer sent from customer. They ask to check if these tables have been normalized. How to check them? Thanks a lot.

ZYT

View 2 Replies View Related

Constraints Across Normalized Tables

Feb 23, 2007

Dear Experts,When I use a single table I can easily use constraints to enforce mybusiness logic, but what do I do when I normalize a single table intomultiple tables.For example, imagine that my initial table has the columns ID, Name,Salary with the constraint that Salary is not NULL. Now imagine thatI break this into two tables, one with ID and Name and another with IDand Salary. I would like to have a constraint that prevents thecreation of a row with (ID,Name) in the first table unless acorresponding row in the second table is also created.I can enforce this logic with triggers, but it looks ugly and isfairly brittle. Is there a better way or is this the dark side ofnormalization?Thanks.

View 6 Replies View Related

Generate A Normalized XML Doc From SQL Server

Jul 20, 2005

I'm trying to generate a normalized XML document out of SQL serverthat reflects the datastructure of a table.Eg. This is what I would like to get<table name='MtFeedback'><field name="MtFeedbackIy" type="int"/><field name="Title" type="varchar" size="50"/><field name="FirstName" type="varchar" size="50"/><field name="Surname" type="varchar" size="50"/><field name="insertedon" type="datetime"/></table>I have tried two ways of and these are the results. The 1st techniqueis closeselect1 as Tag,null as Parent,'' as [table!1],null as [field!2!table-name],null as [field!2!name],null as [field!2!type],null as [field!2!size]UNION ALLselect2 as Tag,1 as Parent,null as [table!1],i.TABLE_NAME as [field!2!table-name],i.COLUMN_NAME as [field!2!name],i.DATA_TYPE as [field!2!type],i.CHARACTER_MAXIMUM_LENGTH as [field!2!size]frominformation_schema.columns iwheretable_name = 'MtFeedback'FOR XML EXPLICIT<table><field table-name="MtFeedback" name="MtFeedbackIy" type="int"/><field table-name="MtFeedback" name="Title" type="varchar"size="50"/><field table-name="MtFeedback" name="FirstName" type="varchar"size="50"/><field table-name="MtFeedback" name="Surname" type="varchar"size="50"/><field table-name="MtFeedback" name="insertedon" type="datetime"/></table>The 2nd technique fails totally.select1 as Tag,null as Parent,i.TABLE_NAME as [table!1!name],null as [field!2!name],null as [field!2!type],null as [field!2!size]frominformation_schema.columns iUNION ALLselect2 as Tag,1 as Parent,null as [table!1!name],i.COLUMN_NAME as [field!2!name],i.DATA_TYPE as [field!2!type],i.CHARACTER_MAXIMUM_LENGTH as [field!2!size]frominformation_schema.columns iwheretable_name = 'MtFeedback'FOR XML EXPLICIT<table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="MtFeedback"/><table name="categories"/><table name="categories"/><table name="products"/><table name="products"/><table name="products"/><table name="descriptions"/><table name="descriptions"/><table name="descriptions"/><table name="syssegments"/><table name="syssegments"/><table name="syssegments"/><table name="sysconstraints"/><table name="sysconstraints"/><table name="sysconstraints"/><table name="sysconstraints"/><table name="sysconstraints"/><table name="sysconstraints"/><table name="sysconstraints"/><table name="dtproperties"/><table name="dtproperties"/><table name="dtproperties"/><table name="dtproperties"/><table name="dtproperties"/><table name="dtproperties"/><table name="dtproperties"><field name="MtFeedbackIy" type="int"/><field name="Title" type="varchar" size="50"/><field name="FirstName" type="varchar" size="50"/><field name="Surname" type="varchar" size="50"/><field name="insertedon" type="datetime"/></table>Cheers Dave

View 1 Replies View Related

Trouble Getting SQL Query To Work Using LIKE Clause With Astersik (*) As Wildcard In ADO.net

Apr 13, 2006

Please help.

Has anyone seen a problem querying Excel or Access database when the "LIKE" clause is used with the "*" wildcard? The problem I'm seeing is that the query fails to return a dataset whenever "*" wildcard is used.



For Example,

sQry="Select * From [EmployeeData$] WHERE Id LIKE 'AAA'" 'query WORKS

sQry="Select * From [EmployeeData$] WHERE Id LIKE 'AAA*'" 'query does NOT WORK

Assume that Table name is "EmployeeData", with "ID", "Name" and "Birthdate" as Fields.

Data:
ID Name Birthdate







AAA
Aaron
5/4/1975

CCC
Charlie
10/14/1948

DDD
Deloris
7/19/1998

The code I use is listed as follows:

Imports System.Data.OleDb


Imports System.Data
Public Class Form1


Private m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _

"Data Source=C:ExcelData1.xls;" & _

"Extended Properties=""Excel 8.0;HDR=YES"""

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


'Use a DataSet to Query data from the EmployeeData table.

Dim QryConn As New OleDbConnection(m_sConn1)

'Dim strQry as string ="Select * From [EmployeeData$] WHERE Id LIKE 'AAA'" '- works

Dim strQry as string ="Select * From [EmployeeData$] WHERE Id LIKE 'AA*'" ' does not work

Dim da As New OleDbDataAdapter(strQry, QryConn)

Dim ds As DataSet = New DataSet

da.Fill(ds)

Dim dr As DataRow

For Each dr In ds.Tables(0).Rows 'Show results in output window

Debug.WriteLine(dr("Id") & ", " & dr("Name") & ", " & dr("Birthdate"))

'Expected output:






'AAA
Aaron
5/4/1975

Next

QryConn.Close()

End Sub

End Class

View 1 Replies View Related

Onverting A Matrix To A Normalized Format

Feb 12, 2007

Jamie writes "I trying to write a SQL solution using embedded and/or dynamic SQL to convert a matrix file to a normalized format."

View 1 Replies View Related

Unnormalized Source Into Normalized Destination

Feb 28, 2008

Hi
I am new to SSIS. Probaly What I am asking is the simple one. But I dont know. I have a requirement. My Data source is Excel file and Destination is SQL Server . Excel file consist around 10k unnormalized rows which should be loaded to the multiple normalized master and child tables into the destination with the Primary key (identity column) and foreign key constrains. Even sometimes package should check for destination database table for matching Source column (Excel) code with the lookup table code (destination lookup table) and get the Primary key of Lookup table and put it into the destination table. Please help me the way to find the solution for this

View 5 Replies View Related

Displaying Data In Datagrid From A Normalized Set Of Tables

Jul 23, 2007

Ok, I'm fairly new to .NET and even newer to the whole database concept.  But, don't run away yet, I'm no idiot and I shouldn't have too hard of a time understanding your responses if you're kind of enough to give them.  That being said, here's my dilemma:I'm trying to make a database of all the movies I own, the actors in them and the genre (s) they belong to. I have a set of tables that are in the 2NF (I think).  I have a movies table, an actors table, a genres table, and two tables called movies_actors and movies_genres with primary-foreign key relationships to pull it all together (e.g. movie_id 1 has two entries in movies_genres, one for Action and one for Drama). My problem arises that when execute my monster query to pull ALL the data on one movie, I get a row returned for every combination of Genres and Actors in a movie.  Example:movie_id            movie_title            comments            actor_first         actor_last            genre_name1                        Casino                  blah blah            Robert               DeNiro               Action1                        Casino                  blah blah            Robert               DeNiro               Drama1                        Casino                  blah blah            Joe                  Pesci                  Action1                        Casino                  blah blah            Joe                  Pesci                  Drama And here's the query that produced that:1 SELECT movies.movie_title, movies.comments, actors.actor_first,
2 actors.actor_last, genres.genre_name
3 FROM movies INNER JOIN movies_actors ON movies.movie_id = movies_actors.movie_id
4 INNER JOIN actors ON movies_actors.actor_id = actors.actor_id
5 INNER JOIN movies_genres ON movies_genres.movie_id = movies.movie_id
6 INNER JOIN genres ON movies_genres.genre_id = genres.genre_id
So, I want to put all the actors for one movie into the same cell in the datagrid (same with the genres) and still keep it sortable by actor or genre.  Is this possible with the .NET 2.0 datagrid?  Do I have some fundamental misunderstanding of how my tables should be structured?  Am I just really far off and acting like a n00b?

View 9 Replies View Related

How-do-I: Add Records (multi-tables) In A Normalized Database

Aug 16, 2007

Hi there -

First of all I think of myself as a software developer and by no means a database expert. So I am posting a question here hoping that someone will lead me in the right direction.

I am somewhat following the database diagram from AdventureWorks with my own "normalized" database and have a question on how to update the table(s).

Here is my situation:
Table: Client
ClientID (PK)
Name
...

Table: Address
AddressID (PK)
AddressLine1
AddressLine2
City
...

Table: AddressType
AddressTypeID (PK)
Name
...

Table: ClientAddress
ClientID (PK1)
AddressID(PK2)
...

The tables should be referenced properly, etc... So my question is, when I add a new Client record, how and when do I update the Client table, Address table and ClientAddress table? If my PK on the Client and Address tables is an autoincriment, do I need it before I can update the ClientAddress table? If so, what do I have to look for, or how do I get the newly created ID to update the ClientAddress?

Is this making any sense? - I'm a little lost/confused. So if anyone can provide me links to where I can learn more about stuff like this and/or post some ideas/solutions, I would greatly appreciate it. Also, if I am not clear on my issue, please ask and I will see if I can clarify it more.

Your help is appreciated in advance!
Bob

View 4 Replies View Related

Split Wide, Denormalized Table Into Normalized Structure

Aug 27, 2002

Thanks for reading.

This is pretty long, hopefully it isn't rambling.

I'm building a system that imports data from several source, Excel files, text files, Access databases, etc. using DTS. The entire process revolved around MS SQL Server, by the way.

I figured I would create denormalized tables that mirror the Excel and flat files, for example, in structure, import data to those, clean up and remove duplicates there, then break those out into my normalized table structure later.

Now I've finished the importing part (though this is going to happen once a week) and I'm onto breaking up the denormalized tables.

I'm hesitating because I'm not sure I've made the best decisions in terms of process, etc.

I've decided to use cursors to loop over the denormalized tables and use batch insert statements to push data out to the appropriate tables.

Any comments? Suggestions? All is welcome.

I'm specifically interested in hearing back on the way I've set up the intermediate, denormalized tables and how I'm breaking them up using cursors (step 2 of the process below). Still, all comments are welcome. As are suggestions for further reading.

Thanks again...

simplified example
(my denormalized tables are 20 - 30 colums wide)

denormalized table:
===================
name, address, city, state, cellphone, homephone


normalized tables:
==================

tblPerson [PK_person, name, age, height, weight]
tblAddress [PK_address, FK_person, street, city, state, zip, addressType]
tblContact [PK_contact, FK_person, data, contactType]


I'm breaking up the denormalized tables like this (*UNTESTED*):
=================================================

DECLARE @vars.... (one for each column in my normalized table structure, matching size and type)

DECLARE myCursor CURSOR
FAST_FORWARD FOR
SELECT name, address, city, state, cellphone, homephone
FROM _DNT_myWideTable
INTO

WHILE @@Fetch_Status = 0
BEGIN
-- grab the next row from the wide table
FETCH NEXT FROM myCursor
INTO @name, @address, @city, @state, @cellphone, @homephone


-- create the person first and get the ID with @@IDENTITY
INSERT INTO tblPerson (name) VALUES (@name)

SET @personID = @@IDENTITY


-- use that ID to coordinate inserts across other tables
INSERT INTO tblAddress (FK_person, address, city, state, addressType)
VALUES(@person, @address, @city, @state, 'HOME')

INSERT INTO tblContact (FK_person, data, contactType)
VALUES(@person, @cellphone, 'CELLPHONE')

INSERT INTO tblContact (FK_person, data, contactType)
VALUES(@person, @homephone, 'HOMEPHONE')

END

View 1 Replies View Related

Review Of DB Design - Normalized, Contraints, Foreign Keys, Etc.

Jul 2, 2004

First of all, this is my initial thread here on dbforums. I come from the land of Broadband Reports and would like to say, Hello fellow DB enthusiasts. :)

I'm not a novice to relational databases (Access MDBs), but new to implementing a db via SQL SERVER (2000 in this case) and using Access Data Projects.

My partial db schema is as follows:

participants
---DID (pk) char(1)
---LID (fk - schools) char(4)
---studentLast varchar(50)
---studentFirst varchar(25)

Sample Data would be
010191M001 | 5671 | SPARKS | JONATHAN
030495F283 | 5671 | DYLAN | CYNTHIA
=====================================

enrollhist (insert/update trigger for enrollactive)
---EID (pk - autonumber) bigint(8)
---EMID (fk - enrollmode) int(4)
---DID (fk - participants) char(10)
---LID (fk - schools) char(4)
---enrollactive bit(1)

Sample Data would be
38173 | 4 | 030495F283 | 9003 | 0
38266 | 3 | 010191M001 | 5671 | 0
39022 | 6 | 030495F283 | 9003 | 0
39036 | 5 | 030495F283 | 9003 | 0
39044 | 4 | 030495F283 | 5671 | 1
39117 | 4 | 010191M001 | 5671 | 1
=====================================

enrollmode
---EMID (pk) int(4)
---mode varchar(25)

Sample Data would be
1 | RECEIVED
2 | WAITING
3 | PENDING
4 | ENROLLED
5 | DROPPED
6 | TRANSFERRED
10 | ORPHANED
11 | DENIED
=====================================

schools
---LID (pk) varchar(4)
---CTID (fk - caltracks) char(1)
---AID (fk - agencies) char(1)
---SDID (fk - schooldist) char(1)
---COID (fk - countydist) char(1)
---sitename varchar(25)
---sitetitle varchar(75)

Sample Data would be
5671 | 3 | 2 | 1 | 4 | ASCOT | ASCOT AVENUE
9003 | 2 | 1 | 4 | 1 | ROWAN | ROWAN AVENUE
2865 | 1 | 3 | 2 | 3 | BRIGHT | BIRDELEE BRIGHT
=====================================

caltracks
---CTID (pk) char(1)
---legend char(4)
---trktitle varchar(15)
---trkcnt int(4)

Sample Data would be
1 | 9030 | 90/30 | 4
2 | CON6 | CONCEPT-6 | 3
3 | SNGL | SINGLE TRACK | 1
=====================================

agencies
---AID (pk) char(1)
---legend varchar(4)
---agencytitle varvhar(50)

Sample Data would be
1 | CRYS | CRYSTAL STAIRS
2 | MAOF | MEXICAN AMERICAN FOUNDATION
3 | PATH | PATHWAYS
4 | CCRC | CHILD CARE RESOURCE CENTER
5 | CHSC | CHILDREN'S HOME SOCIETY OF CALIFORNIA
==========================================

THE REMAINING "FKs" FROM SCHOOL ARE SIMILAR, as is other tables and their relationships. The design of the foreign keys were made using sql and the keyword "REFERENCES" and "FOREIGN KEY."

My questions are: :confused:
(1) Is the use of FK as a Constraint any different than using an INDEX and how?
(2) Should I Alter the Tables to include CASCADING Up/Down?
(3) Are the use of CHARs Ok for the Keys?
(4) Have I over/under-normalized any of the relationships?

View 4 Replies View Related

Stored Proc To Copy Unnormalized To Normalized Table

Jul 20, 2005

I have a "source" table that is being populated by a DTS bulk importof a text file. I need to scrub the source table after the importstep by running appropriate stored proc(s) to copy the source data to2 normalized tables. The problem is that table "Companies" needs tobe populated first in order to generate the Identity ID and then usethat as the foreign key in the other table.Here is the DDL:CREATE TABLE [dbo].[OriginalList] ([FirstName] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[LastName] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[Company] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Addr1] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[City] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[State] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Zip] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Phone] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[Companies] ([ID] [int] IDENTITY (1, 1) NOT NULL ,[Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[CompanyLocations] ([ID] [int] IDENTITY (1, 1) NOT NULL ,[CompanyID] [int] NOT NULL ,[Addr1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[City] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[State] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Zip] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Phone] [varchar] (14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY]GOThis is the stored proc I have at this time that does NOT work. Ituses the last Company insert for all the CompanyLocations which is notcorrect.CREATE PROCEDURE DataScrubSP ASBegin Transactioninsert Companies (Name) select Company from OriginalListIF @@Error <> 0GOTO ErrorHandlerdeclare @COID intselect @COID=@@identityinsert CompanyLocations (CompanyID, Addr1, City, State, Zip) select@COID, Addr1, City, State, Zip from OriginalListIF @@Error <> 0GOTO ErrorHandlerCOMMIT TRANSACTIONErrorHandler:IF @@TRANCOUNT > 0ROLLBACK TRANSACTIONRETURNGOThanks for any help.Alex.

View 3 Replies View Related

Denormalized Access Table To Normalized Database TableS

Apr 17, 2006

Hello,

I am pretty new to SSIS, so please excuse me if this is a trivial question.

I have a denormalized database table in an Access database that I need to import into several different tables in a SQL 2005 database. You can think of the Access table as a CustomerOrders table. For example customer related information (i.e. CustomerName, CustomerID, etc...) is repeated with each record in the Access table. When this data gets moved to the SQL 2005 database, I need to insert one record for each distinct CustomerName/Customer ID record into a Customers table. I then need to insert and link every "Order" record into an "Orders" table.

I am sure that this is probably a pretty common task, but I have not found any examples or articles explaining this particular situation. What ways can this be done?

I was thinking I need to loop through each DISTINCT Customer record in the Access (source) table and insert a Customer record into the destination database's Customer table. I would then need to iterate through each row of the Access (source) table and "Lookup" the appropriate CustomerID/Key Field and insert an "Order" record.

The Access table contains over 75,000 rows of data. I am looking for the most appropriate way of doing this with SSIS (so that I don't have to write a custom application to do this!). Any help, input, links, articles, etc. is appreciated!!

TIA

-Brian

View 1 Replies View Related

Trouble With An ASync Query To Insert A Record And Return The Auto Number Field.

Aug 31, 2007

I get this error when I look at the state of my SQLresults object. Have I coded something wrong?Item = In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.  conn.Open()
Dim strSql As String

strSql = "INSERT INTO contacts (companyId, sourceId, firstName, lastName, middleName, birthday, dateCreated)" _
& "VALUES ('" & companyId & "', '" & sourceId & "', '" & firstName & "', '" & lastName & "', '" & middleName & "', '" & birthday & "', '" & now & "') SELECT @@IDENTITY AS 'contactId'"

Dim objCmd As SqlCommand
objCmd = New SqlCommand(strSql, conn)

Dim aSyncResult As IAsyncResult = objCmd.BeginExecuteReader()

If aSyncResult.AsyncWaitHandle.WaitOne() = True Then


Dim sqlResults As SqlClient.SqlDataReader

sqlResults = objCmd.EndExecuteReader(aSyncResult)

Dim cid As Integer



cid = sqlResults.Item("contactId")
Me.id = cid
conn.Close()
Return cid
Else
Return "failed"


End If  

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved