Simple Simple Linking Tables & Perform Calculation
Mar 22, 2007found it
View 3 Repliesfound it
View 3 RepliesHey,
I have MS SQL database.
I have procedure:
code:--------------------------------------------------------------------------------
CREATE PROCEDURE dbo.Reg_DropTable
@ModuleId varchar(10)
AS
declare @TableName varchar, @kiek numeric
set @TableName = 'reg_'+@ModuleId
begin
DROP TABLE @TableName <- HERE I GOT ERROR
end
GO
--------------------------------------------------------------------------------
I got error when using variable with tables names.
How to do this?
Ps. Number is send to this function and it must drop table with name Reg_[That number]
If I have a table called 'areas' as below which i'm using in a web app:
Code:
area_id mediumint(9) NO PRI auto_increment
name varchar(45) NO
postcode char(4) NO
o4s_coords varchar(15) YES
gm_coords varchar(200) YES
description text NO YES
filename varchar(30) YES
width smallint(4) YES
height smallint(4) YES
comment varchar(255) YES
This table is not going to ever hold more than 600 records. About 550 will only use the first 3 fields (area_id,name,postcode). Is it advisable to break this into 2 separate tables or given the small amount of content is it ok with some null fields?
Hi there,
it seems like an easy query here. I have 3 tables:
Forums (ID. ForumTitle)
Topics (ID, TopicTitle, ForumID)
Posts (ID, PostTitle, TopicID)
and data
Forums
1, FTitle#1
2, FTitle#2
3, FTitle#3
Topics
1, TTitle#1, 1
2, TTitle#2, 1
3, TTitle#3, 1
4, TTitle#4, 2
Post s
1, PTitle#1, 1
2, PTitle#2, 1
3, PTitle#3, 2
4, PTitle#4, 3
5, PTitle#5, 4
I need to count for each forum the number of Topics and Posts so it will look like that (Forums.ID, Forums.ForumTitle, TotalTopics, TotalPosts):
1, FTitle#1, 3, 4
2, FTitle#2, 1, 1
3, FTitle#3 0, 0
How can I achieve that ?
Can anybody tell me, how to write a T-SQL loop,
that goes through all tables in a database to
realize some updates there?
Thanx a lot in advace
Gert
Hello, this is probably the most helpful forum I have found on the Net in awhile and you all helped me create a DB for my application and I have gotten kind of far since then; creating stored procedure and so forth. This is probably very simple but I do not yet know the SQL language in depth to figure this problem out. Basically I have a printer monitor application that logs data about who is printing (via logging into my app with a passcode, which is located in the SQL DB), what printer they are using, and the number of pages. I have 3 tables, one called 'jobs' which acts like a log of each print-job, a user table (which has data like Name=HR, Passcode=0150) and table listing the printers. Each table uses an integer ID field which is used for referencing and so forth. Tables were created with this command sequence:
create table [User_Tbl](
[ID] int IDENTITY(1,1) PRIMARY KEY,
[Name] varchar(100),
[Password] varchar(100),
)
go
create table [Printer_Tbl(
[ID] int IDENTITY(1,1) PRIMARY KEY,
[Name] varchar(100),
[PaperCost] int
)
go
create table jobs(
[JobID] int IDENTITY(1,1) PRIMARY KEY.
[User_ID] int,
Printer_ID int,
JobDateTime datetime,
NumberPrintedPages int,
CONSTRAINT FK_User_Tbl FOREIGN KEY ([User_ID])
REFERENCES [User_Tbl]([ID]),
CONSTRAINT FK_Printer_Tbl FOREIGN KEY ([Printer_ID])
REFERENCES Printer_Tbl([ID])
)
go
I need display some data in a datagrid (or whatever way I present it) by using a query. I can do simple things and have used a query someone on here suggested for using JOINS, and I understand but I can't figure out how to make this particular query. The most necessary query I need for my report needs to look like this: (this will be from a data range @MinDate - @MaxDate)
Username PagesOnPrinter1 PagesOnPrinter2 TotalPagesPrinted Cost
--------- ---------------- --------------- ---------------- ----
HR 5 7 12 .84
Finance 10 15 25 1.75
So it gives the username, how many pages printed on each printer, the total pages printed, and the total cost (each printer has a specific paper cost, so it is like adding the sum of the costs on each printer). This seems rather simple, but I cannot figure out how to translate this to SQL.
One caveat I have is that the number of printers is dynamic, so that means the the columns are not really static. Can this be done? And if so how can I go about it? Thanks everyone!
So these are a couple different interpretations I've made of a statement that needs to return students name's with the OSOS field in the attendcode code column of the attendance table on todays date with an attendance.aperiod column equal to 4.
This first one returns no results at all when I should get about 7 rows or so.....
Select Student.name,
attendance.studentid,
attendance.attenddate,
attendance.aperiod,
attendance.attendcode
from Attendance, Student
where AttendDate >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)
And AttendDate < DateAdd(Day, DateDiff(Day, 0, GetDate()), 0) + 1
And aperiod = '4'
And AttendCode = 'OSOS'
AND student.name = Attendance.studentid
This one is returning all of the names in the database 6 times each.
Select Student.name,
attendance.studentid,
attendance.attenddate,
attendance.aperiod,
attendance.attendcode
from Attendance, Student
where AttendDate >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)
And AttendDate < DateAdd(Day, DateDiff(Day, 0, GetDate()), 0) + 1
And aperiod = '4'
And AttendCode = 'OSOS' order by name
I think something is messed up with my WHERE control but I cant figure it out... Any help is greatly appreciated!
I need a sql statment to return a list of tables for a given databasewhere the Recovery Model option is Simple.TIARob
View 5 Replies View RelatedExperienced memebers,
I have what should be simple question about related tables in a dataset and using those fields in a report. Here is my simple design.
Order Header -> Line Item -> Line Discount -> Discount Table
Now when designing this report I cannot seem to access the related discount records for the line item. (as more than one can be applied) Every time I try to drag an field from one of the tables in the dataset to my report it automatically adds "First()" onto the field value expression. This seems to work fine for the order header, but doen't even come close to getting the right discount on the line item? I basically need to pass through the Line Discount table to get to the discount name field to put on the same line as my line item data on the report.
I have looked and googled for for an example on this, but have come up short. Can anyone point me in the right direction?
Thanks,
Chris
i have a form where I ask a number of questions
The answer for each question is a drop down menu ...
The person chooses one or many from the answer ....
e.g I would like a wrist band for Trip A (cost £6) {WristA}
I would like a wrist band for Trip B (cost £8) {WristB}
I would like wrist band for Trip C (cost £4) {WristC}
etc etc ....
I would like to grab thes responses from the form
and write SQL script to perform the total cost of wristbands...
Any ideas on how I can do this in SQL - the 'tokens' are available in SQL (i.e. {WristA} , {WristB}, {WristC})
hi all, i wasnt quite sure where to look to answer my particular problem so i am posting up this thread in the hopes that someone can point me in the right direction. in my report, i am showing sales figures for an area. i added a table to display sales from this year, sales from last year, and then the comparable percentage('this' divided by 'last' and then minus one). to account for some ppl who didnt have sales last year, i was able to use an IIF expression to return "N/A" in the textbox. my problem is i want the compared percentage to show for the area total, but not including ppl who were an 'N/A'. i am assuming that some sort of expression will be needed for the area total row, i.e. i want the area total to sum up this year and last year and then get the percentage, but i need to filter out the individuals who didnt have data for last year.
as an example
nsty nsly percentage
total: 15 7 X
A: 5 4 25%
B: 5 3 66%
C: 5 0 N/A
the percentage for total, X, should be (10/7)-1, with p0 as the format; right now it is summing rows A, B, and C.. how can i exclude row C from the calculation?
am i on the right track by researching filters and expressions, or is this a matter for the query
thanks in advance for any help
I need just the names of tables, views and sprocs within a SQL Serverdatabase. What's the easiest way to do this?
View 3 Replies View RelatedI am receiving funny results from a query. To simplify, I have 2 tables (todayyesterday). Each tbl has the same 8 columns. My query joins the two tables then looks where either of two columns has changed. What is happening is that when checking one of the columns it seems as though sql is flipping the column, causing it to be returned in error.
result set
colA colB colC colD colE colF colG colG (from yesterday)
1 1 a b c d e m
1 1 a b c d m e
So what's happening is that the record above is actually the same record and should not be returned. There is a daily pmt column that changes but I am not using that in the query. Aside from that the two records are identicle.
Any help is appreciated.
Hi,
I have the following situation (with a site that already works and i cannot modify the database architecture and following CrossRef tables -- you will see what i mean by CrossRef tables below)
I have:
Master table Hotel
table AddressCrossRef (with: RefID = Hotel.ID, RefType = 'Hotel', AddrID)
joins
table Address (key = AddrID)
table MediaCrossRef (with RefID = Hotel.ID, RefType= 'Hotel', MediaID)
joins
table Media (with MediaID,mediaType = 'thumbnail')
foreach hotel, there definitely is a crossRef entry in AddressCrossRef and Address tables respectively (since every hotel has an address)
however not all hotels have thumbnail image
hence i have hotel inner join AddressXReff inner join Address ..... however i must have
left outer join mediaXref left outer join media
the problem is that if there is no entry in Media or mediaXref, I don't get any results
i tried to get over it by using
where (media.mediaTyple like 'thumbnail' or media.mediaType is null)
but then i started getting multiple results for each hotel because media's of type movie or full_image or etc... all got returned
any clue?
thanks
...when I started this endeavor.
I have a previously developed Lotus Notes App. The idea was simple; as
I am sefl taught on Lotus Script, I figured I'd be able to stumble my
way through VB.Well,
it started OK. I used VB Express to get familiar with the stuff, but
decided to go with a full version of VS 2005 and try and get this thing
properly developed as a web app. I purchased several reference books
etc., and have become relatively familiar with the forums here.First
issue I have is that I simply want to use code to update or add records
to an SQL DB. I know about datagridview etc., but I want to update the
DB using forms, not the tabular view those controls provide. I thought
it would be relatively straight forward, but found my ignorance runs
deeper than I thought. When I tried to do so I am finding I am not
really clear on where to make declarations etc. in the web app. If anyone could point me in the right direction that would be great. The
issue with searching these forums is most posts deal with datagridview
or something similar.I have spent a ton of time trying to find relevant
posts or articles, but have had no luck yet.Again, all Ireally
need is a nudge in the right direction. I am more than willing to plod
through reference materials or articles/posts to find what I need to
know, I just can't find where to even start on the info I need. Regards, Joe
Hi
I have a problem with my sql WHERE query, if i manually type ([Area] = 'The First Area') then it is okay but if i try and pass the variable 'The First Area' using the
([Area] = @Area) it doesnt work.
ALTER PROCEDURE dbo.StoredProcedure1(@oby nvarchar,@Area char,@Startrow INT,@Maxrow INT, @Minp INT,@Maxp INT,@Bed INT)ASSELECT * FROM(SELECT row_number() OVER (ORDER BY @oby DESC) AS rownum,Ref,Price,Area,Town,BedFROM [Houses] WHERE ([Price] >= @Minp) AND ([Price] <= @Maxp) AND ([Bed] >= @Bed) AND ([Area] = @Area)) AS AWHERE A.rownum BETWEEN (@Startrow) AND (@Startrow + @Maxrow) Please Help I know it must be something simple as the sql works but not when i pass the variable.... Thanks In Advance
How can i get an output like this from this sql??
HEM_PATIENT_ID is primary key...
Output:
First row: initial values of the fields
Second row: average of the same fields
Please help me...
select * from (
select HEM_LOKOSIT, HEM_NNS
from LPMS.HEMOGRAMS
where HEM_PATIENT_ID = 33
union
select AVG(HEM_LOKOSIT), AVG(HEM_NNS)
from LPMS.HEMOGRAMS
where HEM_PATIENT_ID = 33)
order by HEM_LOKOSIT desc nulls last;
Am new to SQL Server , can any1 tell me is there anyway to display date in this format month and year like Apr 2000 ,excluding the day.
eg: 01/28/2000 should b displayed like Jan 2000
Hi,
I'm relatively new to SQL7 but I did use 6.5 a fair bit.
I'm trying to test the restore of the Transaction log backup and having a bit of difficulty. The idea is that I make a complete database backup at 1am backup the transaction log every 30 minutes between 7am and 7pm. I need to be able to restore the database to a known state between 7am and 7pm with a max data loss of 30 minutes.
What I am trying to achieve is (as a test):
1)Create a small test database with a test table
2)Add some data to the test table
3)Back up the transaction log
4)Restore the transaction log to 'undo' the data added in step 2
Should be simple I think !!! The problem I am encountering is that in step 4 it won't let me restore only the transaction log (a tick automatically appears in the database backup as well). Bah !
Can someone please tell me what simple steps are required to get this to work. I need specifically on what options to chose during the backup and restore processes.
Thankyou,
Tim
Given one table with one column and two rows, one containing the string 'Bill', one containing the string 'Gates'.
Write a select statement which gives you the result 'Bill Gates'.
???+
Hi All,
I have a table with 2 columns which looks like the following.
IDText
-------------
1AAA
1BBB
1CCC
2DDD
2EEE
2FFF
3GGG
3HHH
3III
Each ID can have multiple texts associated with it. I want to write a query that gives me the following output.
IDText
-------------
1AAA; BBB; CCC
2DDD; EEE; FFF
3GGG; HHH; III
I appreciate your help
Thanks
Hi All,
I have a table with 2 columns which looks like the following.
IDText
-------------
1AAA
1BBB
1CCC
2DDD
2EEE
2FFF
3GGG
3HHH
3III
Each ID can have multiple texts associated with it. I want to write a query that gives me the following output.
IDText
-------------
1AAA; BBB; CCC
2DDD; EEE; FFF
3GGG; HHH; III
I appreciate your help
Thanks
Hi,
I have a table with two columns. I need to find distinct value of col1 and the correspondin repeated value of col2 for that col1 value with comma seperated list. Is there any function
for this in MS SQL?
I need somethgn like
a 1,2,3
b 4,5
c 7
d 5,55,5
I can do that with creating 2 cursors but looking for some easy way around.
Any suggestion and help highly appretiate.
Thanks
incorrect syntax near #
how do i fix this and did i make any other errors?
SELECT Master.CheckNum, Master.CheckDate, Master.ExpenseType, Deal.Alias, Detail.InvoiceDate, Detail.InvoiceAmount, Detail.Person, Detail.Deal, Detail.InvoiceNum, Detail.Reference, Detail.idDetial
FROM Master INNER JOIN (Deal INNER JOIN Detail ON Deal.Deal = Detail.Deal) ON Master.CheckNum = Detail.CheckNum
WHERE (((Master.CheckDate)>#12/5/2005#) AND ((Deal.Alias)="aic"));
Originally i had:
DELETE FROM #RptDetails WHERE StructureType <> @StructureType
AND #RptDetails WHERE #RptDetails.TraderId <> @TraderId OR #RptDetails.TraderId is null
But it didnt delete the structure types i changed to :
DELETE FROM #RptDetails WHERE StructureType <> @StructureType --AND
DELETE FROM #RptDetails WHERE #RptDetails.TraderId <> @TraderId OR #RptDetails.TraderId is null
and it did, how do i format the 2nd sql into 1 statement and what was i doing wrong?
Hi,
How do I sum all of the returned values into my output param ? This returns multiple rows, all data is oftype decimal.
Thanks
Bob
ALTER proc
spPSICalcA9
@iReturn int output,
@Contract varchar (8)
as
Select
sd.HoursLostRain,
sd.HoursLostMaxT,
sd.HoursLostMinT,
sd.HoursLostFrost,
sd.HoursLostWind,
sd.HoursLostVis
from
SiteDiary sd
where
sd.Contract = @Contract
"I dislilke 7am. If &am were a person, I would kick 7am in the biscuits." - Paul Ryan, dailyramblings.com
Hi,
I need to return all records where ..
Contract = @Contract
AND
CrossReference is null or ""
I have this but I dont think its right..
Bob
where
a.Contract = @Contract AND a.crossreference is null OR a.crossreference = ""
"I dislilke 7am. If &am were a person, I would kick 7am in the biscuits." - Paul Ryan, dailyramblings.com
I think it's simple, but I can't get it to work.In English its: find records in TableA where the field [Field1] hasmore than one unique value in Field2sample records in TableAField1 Field22241 123452241 123452242 123452242 99856desired return (2 records)2242 123452242 99856thank you for your helpPaul
View 3 Replies View RelatedI have a form that after being filled out has its contents written to adatabase and then goes to confirmation .asp page. I want the confirmationpage to be personalized but I am not sure how to pass the "name" parameterto the confirmation.asp page. I know I am going to kick myself whrn I seethis.Thanks, Houston
View 7 Replies View RelatedGreetings,
I'm trying to find out if a particular column in a table has more than 10 digits. for example: the TN column.
How can I write this query? The data type for this column is bigint. Also, would it be better to change this data type to char(10) instead as it's used primarily for phone # lookups? Thanks in advance!
ID TN
1 7132483234
this is the query I need help with
select a.RecordID,a.RelocateID,a.WhenConfirmed,b.RequestI D,b.DocumentID,b.RequestWhen from RelocateeDTA a inner join
docRequests b on ({a.RecordID}=' + CONVERT(VARCHAR, a.RecordID)'= b.WhereClause)
because I am trying to link RelocateeDTA that has RecordID to docRequests that has the same piece of data in field WhereClause but is a varchar, and I am getting an error message (syntax error or access violation)
Could somebody help me please
dear experts,
i have two tables, tblcustomer and tblform. in tblcustomer i have cutomerid PK and i have also a field that link these two tables customername. in tblforms i have formname. customername and formname are not PK and customername has a lot of null values.
my question is that i want to link these two tables in customerid not the name and also to get the forms used by this customer. the thing is that i have to write a join query.
any suggestion to do that?
thanks my friends
I know it's possible to link tables between Access and SQL Server using ODBC....however can u use DAO to do this? If there's a way i would appreciate some help. Thanks in advance.
View 2 Replies View Related