Syntax On A Join And RIGHT Function

Mar 31, 2005

Hi,

Trying to join two tables together.

Select * from ...

inner join

on table1.ID = table2.ID;


this works fine, however i want to use the RIGHT function so that i get the last four digits of the ID. this causes a parse error:

inner join on table1.right([ID],4) = table2.right([ID],4);

searched a bit but couldn't find a way to do what im trying to accomplish. is there a proper syntax?

thanks!

View 1 Replies


ADVERTISEMENT

Which Is Faster? Conditional Within JOIN Syntax Or WHERE Syntax?

Mar 31, 2008

Forgive the noob question, but i'm still learning SQL everyday and was wondering which of the following is faster? I'm just gonna post parts of the SELECT statement that i've made changes to:

INNER JOIN Facilities f ON e.Facility = f.FacilityID AND f.Name = @FacilityName

OR

WHERE f.Name = @FacilityName


My question is whether or not the query runs faster if i put the condition within the JOIN line as opposed to putting in the WHERE line? Both ways seems to return the same results but the time difference between methods is staggering? Putting the condition within the JOIN line makes the query run about 3 times faster?

Again, forgive my lack of understanding, but could someone agree or disagree and give me the cliff-notes version of why or why not?

Thanks!

View 4 Replies View Related

Left Join Vs Left Outer Join Syntax Generates Different Execution Plans

Apr 16, 2008



Anyone know why using

SELECT *
FROM a LEFT OUTER JOIN b
ON a.id = b.id
instead of

SELECT *
FROM a LEFT JOIN b
ON a.id = b.id

generates a different execution plan?

My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".

Any enlightenment is very appreciated.

Thanks

View 5 Replies View Related

Bad Join/where Syntax

Mar 29, 2004

Monitoring a sql 2000 server where a vendor app is running. Looking at a poor performing sql and I saw the following in the where clause
WHERE immunization_mast_.account_id =* p.account_id AND
immunization_mast_.case_id =* p.case_id

What is the meaning of the =*, have not seen this before?

View 2 Replies View Related

Need Syntax Help In Join From Two DB

Jun 15, 2004

Hi

I have two databases on my server, I need a simple query with one join between one table from each database.
I looked in the help of FROM clause and found the Argument "table_source" where it explains this :
"If the table or view exists in another database on the same computer running Microsoft® SQL Server™, use a fully qualified name in the form database.owner.object_name".

Can someone please help me fill the variants ??
My DB name is "Forum" the owner is "DBRNDAdministrator" and the table name is "TblUsers", so I tried to write in the FROM clause :
"FROM Forum.DBRNDAdministrator.TblUsers" but it doesn't work... so anyone have any idea how should it be ?

Thanks,

Inon.

View 4 Replies View Related

Out Join Syntax

Jul 25, 2007

Hello,

I need to write and Ansi Outer Join that has 2 columns from the same table.

I keep getting

Server: Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "dim_person.person_key" could not be bound.

here is what the code looks like. any help is appreciated.

select ...

from dim_day_of_year
, dim_company
, dim_currency
, dim_account
, dim_person
, ods_conference
left outer join fact_usage_alloc fua1 on ods_conference.conf_key=fua1.conf_key
left outer join fact_usage_alloc fua2
on dim_person.person_key=fua2.requestor_person_key

where...

View 9 Replies View Related

Join Syntax Help

Jul 23, 2005

I am trying to figure out some sql syntax, and I could use some help. Thisis my first atempt at joins, so bear with me.I have a table (A) which looks like the followingID Data Source-------------------------1 abcdef 1002 abcdef 1003 abcdef 2004 abcdef 2005 abcdef 200A second table (B) which looks like the followingKey ID------------------------Key1 1Key1 2Key1 3Key1 4Key2 1Key2 2Essentially, A is a table of items, and B is a table of where those itemshave been used (Key1 is like an invoice which has items 1-4 on it, Key2 is asecond invoice with 1 and 2.) Source, in table A, is like the itemsupplier.I would like to get a list of every invoice (Key) that has used a part (ID)from a particular Source.So, for example, I would like to query for source 100 and get back (Key1,Key2) or query for source 200 and get back only Key1.To this end, I tried"SELECT DISTINCT B.Key FROM B JOIN A ON (B.ID = A.ID) WHERE (A.Source =100)"But I got an empty recordset, so something is amiss.Any help is greatly appreciated.Thanks,-d

View 2 Replies View Related

SQL JOIN SYNTAX

Jul 20, 2005

Erland Sommarskog <sommar@algonet.se> wrote in messagenews:Xns93EFA9C57954AYazorman@127.0.0.1...[color=blue]> MAB (fkdfjdierkjflafdafa@yahoo.com) writes:[color=green]> > What I want is the sum of the amounts of the last payments of all> > customers. Now the last payment of a customer is not necessarily the one> > with the highest paymentid for that customer BUT it is the one with the> > highest paymentid on the MOST RECENT date. We dont keep the time part> > just the date so if there are more than 1 payments of a customer on a> > date ( and there are many such cases ) only then the paymentid decides> > which is the last payment. Further the last payment may be the last as> > of today but I may want to find the sum of all the last payments upto> > say March 1, 2003 or any date. My own solution is too slow even it is> > correct.[/color]>> This solution is not tested, as you did not provide any sample data:>> SELECT SUM(p3.amount)> FROM Payments p3> JOIN (SELECT paymentid = MAX(p2.paymentid)> FROM Payments p2> JOIN (SELECT p1.customerid, mostrecent = MAX(p1.date)> FROM Payments p1> WHERE p1.date <= '20030301'> GROUP BY p1.customerid) AS p1> ON p1.customerid = p2.customerid> AND p1.mostrecent = p2.date) AS p2> ON p3.paymentid = p2.paymentid>> This solution is for SQL Server only. I don't know Access, so I can't> help with that.>> As for performance, this is likely to be a case of finding the best> indexes. Clustered on (date, customerid) and nonclustered in (paymentid)> maybe.[/color]Thanks. This looks fascinating. It looks correct too (although I haventfully verified that). From this my next questionIs it possible to write your query in older join syntax likeFROM Payments p1, Payments p2WHERE p1.customerid = p2.customerid etc.Or is it that the newer syntax is superior such that you can do things withit that you cant do with the older one?I cant see how to write such a query the older way because you have only oneSELECT Clause thereMany thanks again

View 4 Replies View Related

Help With Join Syntax

Jun 29, 2006

I have a query where I need to join a table to multiple tables and alias a field from those tables on each join. I tried the syntax below but received a error. Please assist, first time trying to do this.

JOIN dbo.AbsenceReason ar ON ar.AbsenceReasonID = sda.AbsenceReasonID

WHERE ar.[Name] = 'DailyReason'

LEFT JOIN dbo.AbsenceReason ON ar.AbsenceReasonID = spa.AbsenceReasonID

WHERE ar.[Name] = 'PeriodReason'

LEFT JOIN dbo.AbsenceReason ON ar.AbsenceReasonID = cio.AbsenceReasonID

WHERE ar.[Name] = 'CheckInOutReason'

error I receive is :

Msg 156, Level 15, State 1, Procedure p_000001_GetAttendanceProfileData, Line 45

Incorrect syntax near the keyword 'LEFT'.

Msg 102, Level 15, State 1, Procedure p_000001_GetAttendanceProfileData, Line 63

Incorrect syntax near ')'.

View 12 Replies View Related

Need Help On Complex Join Syntax ???

Mar 3, 2008

 Hi guys, I'm still new around here and still a noob for sql. Can you give me some example for some joins from the easy ones to the most complex and all of it kinds, I heard that there's a lot of different kind of join in sql. You can give me some link or maybe some code examples for me, I appreciate all kinds of help . Thanks for all your help. Regards. 

View 3 Replies View Related

New Outer Join Syntax

Aug 19, 2002

Hi,

Can anyone please tell me how can i convert the following query in
the old join syntax to the new join syntax so that it returns the same
results? I tried converting it, but it returns different reuslts.
please help me as it is urgent.

OLD Syntax:
===========

SELECT
....................
..<column_list>......
FROM
dbo.ASSET_BOOK AL1,
dbo.ASSET_BOOK AL2,
dbo.ASSET_HEAD AL3,
dbo.ASSET_BOOK AL4,
dbo.ASSET_BOOK AL5
WHERE
(AL1.U##ASSETNO =* AL3.U##ASSETNO
AND AL3.U##ASSETNO *= AL2.U##ASSETNO
AND AL4.U##ASSETNO =* AL3.U##ASSETNO
AND AL3.U##ASSETNO *= AL5.U##ASSETNO)
AND
(AL1.U##BOOKCODE = 'USGAAP'
AND AL2.U##BOOKCODE = 'CONSUSD'
AND AL4.U##BOOKCODE = 'ICP'
AND AL5.U##BOOKCODE = 'STETC'
)


New Syntax:
===========

SELECT
COUNT(*)
FROM dbo.ASSET_BOOK AL1
RIGHT JOIN dbo.ASSET_HEAD AL3
on AL1.U##ASSETNO = AL3.U##ASSETNO
LEFT JOIN dbo.ASSET_BOOK AL2
on AL3.U##ASSETNO = AL2.U##ASSETNO
RIGHT JOIN dbo.ASSET_BOOK AL4
on AL4.U##ASSETNO = AL3.U##ASSETNO
LEFT JOIN dbo.ASSET_BOOK AL5
on AL3.U##ASSETNO = AL5.U##ASSETNO
AND
AL1.U##BOOKCODE = 'USGAAP'
AND AL2.U##BOOKCODE = 'CONSUSD'
AND AL4.U##BOOKCODE = 'ICP'
AND AL5.U##BOOKCODE = 'STETC'

Thanks in advance.

Rafi

View 2 Replies View Related

Syntax For Table Join

May 23, 2006

Is there a way to join 2 tables from different databases on the same instance? If so, what is the syntax? For example I have an instance called TEST with 2 databases (DB1 and DB2). Each database have a table (DB1.TABLE & DB2.TABLE). Both tables have a common column called ID.
Can both tables be joined in a query?

TIA.

View 5 Replies View Related

Inner Join Syntax Error

Jun 10, 2008

I am getting the error message:

Msg 156, Level 15, State 1, Line 62
Incorrect syntax near the keyword 'inner'.
Msg 102, Level 15, State 1, Line 62
Incorrect syntax near 'Code'.

When I attempt to run the following query:

select NewUsed, VehicleYear, VehicleMake, VehicleModel, VehicleTrim,
AppZip, ltrim(newtrademake) AS TradeMake, ltrim(trademodel)TradeModel,
TradeYear, NcodeL AS TradeNcodeL, NcodeM AS TradeNcodeM, OwingOnTrade, TradeAllowance, NetTradeIn

from
(select *,

Case

When TradeMake = ' Ford' and (Trademodel like '%Aerostar%' or Trademodel like '%Bronco%')
Then 'FORD TRUCKS'

Else ltrim(TradeMake)
End

AS NewTradeMake
from dbo.vw_dds)


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

on code.make = ltrim(newtrademake) and code.model= ltrim(trademodel) and code.modelyear = tradeyear

The error is related to the inner join but I can't seem to figure out what I am doing wrong.

Thank you for your help,
Tasha

View 5 Replies View Related

Syntax To Join With And Statement

Jan 17, 2014

I inherited a query and I am getting an error of Unsupported literal in join in the INNER JOIN FRDM.dbo.MEMBER_SUBSC FRDM_dbo_MEMBER_SUBSC2

ON (frdm.dbo.CLAIM_HEADER_WITH_VOIDS_VIEW.SBSB_CK = FRDM_dbo_MEMBER_SUBSC2.SBSB_CK AND FRDM_dbo_MEMBER_SUBSC2.MEME_SFX
= '00')statement. Specifically the AND FRDM_dbo_MEMBER_SUBSC2.MEME_SFX
= '00')part.
SELECT frdm.dbo.CLAIM_HEADER_WITH_VOIDS_VIEW.GRGR_ID AS 'group number'

[code]....

View 1 Replies View Related

Question About JOIN Syntax

Jul 20, 2005

what is the syntax to join a table with the result of antoher query.For example i have two tablesCreate Table Customers (CustomerID int,LastPaymentDate Datetime )Create Table Payments (PaymentID int,CustomerID int,PaymentDate Datetime )What query will bring me the customers whose lastpaymentdate in thecustomers table is not correct.That can only be checked by comparing it with the max paymentdate for eachcustomer in the payments table.I want this to be done by ansi standard sql. Not using any specific featureof sql server.thx

View 11 Replies View Related

Outer Join Syntax

Jul 20, 2005

I am now working on SQL Server 2000 having had previous experience ona different database. Both of the OUTER JOIN syntaxes is differentfrom what I am used to and I am finding it slightly confusing.For example, given two tables :wipm_tbl_miwipm_tbl_wi (which may not have data in it for a specific record thatexists in the first table.)If I use the old style syntax :SELECT mi.workitemid, wi.datavalueFROM wipm_tbl_mi mi , wipm_tbl_wi wiWHERE mi.workitemid *= wi.workitemidAND mi.workitemid = 1AND wi.dataname = 'XXX'I get back1,NULLwhen there is no matching record in wipm_tbl_wi, which is what Iexpect.However, if I try to use the SQL-92 syntaxSELECT mi.workitemid, wi.datavalueFROM wipm_tbl_mi miLEFT OUTER JOIN wipm_tbl_wi wiON mi.workitemid = wi.workitemidWHERE mi.workitemid = 1AND wi.dataname = 'XXX'I don't get anything back. Please can someone help me understand whatis wrong with the bottom query.Thank you,Martin

View 2 Replies View Related

SQL Syntax - INNER Or OUTER JOIN Vs. WHERE

Jul 20, 2005

I apologize if this has been asked before- I searched google but couldnot find a concrete answer.I recently inherited a database whose t-sql code is written in a formatthat I find difficult to read (versus the format I have used foryears).I have tested the queries below using the SQL Profiler, and both haveidentical costs. Is there any advantage of one format over the other?Format 1:---------SELECT *FROM Customers c, Orders oWHERE c.CustomerID = o.CustomerIDFormat 2:---------SELECT *FROM Customers cINNER JOIN Orders AS o ON c.CustomerID = o.CustomerIDIs it just a matter of personal preference? Does the same hold true forusing OUTER JOIN versus the old *= or =* ?Thanks,Matt

View 3 Replies View Related

Update Join Syntax From *=

Oct 29, 2007

Team,

Our product was written against an older version of SQL and the non-ANSI standard join operators (*= and =*). Our group is now looking to move our database to SQL Server 2005.

We are now faced with updating a lot of legacy queries that use this method of joins and I was hoping for a shove in the right direction.

I have run across a query similar to the following:
SELECT <many fields go here>
FROM a, b, c, d, e, f, g, h
WHERE a.fld1 *= d.fld1
AND e.fld3 *= h.fld3

The query, as it is with the non-ANSI join operators, returns a single record. For the life of me, I cannot figure out how to format the FROM statement to create the LEFT OUTER JOIN statement(s) to get the query to work.

The SQL Server 2005 books online seems to be lacking in the area of examples where you have multiple joins using different tables; they focus on one table joining against multiple tables instead.

Anyone have any reading suggestions or other ideas on how to get this to work?

Thanks.
Richard

View 13 Replies View Related

SQL Compataiblity For *= Join Syntax

Feb 27, 2007

I'm looking at upgrading to SQL2005 and have found the following issue with some old t-sql we have.

We have some views that are created using the old outer join syntax of *=. If I run the SQL in query analyzer, it runs fine...but if I create a view with the SQL, when I query the view I get the error:



Msg 0, Level 11, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.

Msg 0, Level 20, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.



I tried changing the database compatibility level all the way back to 7.0, and recreating the view (still using *=), but still had the same error.

Is it possible to have a view that uses this old syntax with SQL2005? How? I don't want to have to find/rewrite everything very quickly.

thanks,

Matt

View 11 Replies View Related

IRR Function Syntax?

Jul 19, 2007

I have a question about the syntax of the IRR function in reporting services 2005. Basically I have a table with 5 rows. I'd like to plug a column of data into the IRR function as an array (which is what it takes). Not sure how to convert a column into an array in an expression.



Any help would be appreciated... thanks!





Ben Lieb

ben.lieb@tekelec.com

View 7 Replies View Related

Syntax Struggle On Table Join

Jan 16, 2007

Hello
I am trying to join 2 tables listing product names but I can’t get the syntax quite right.
 
I have managed to get the 2 tables to display separately.
 
Table #1:
Select
ProductName as [Product Name]
From
Product_CatA
Where Auto = 'yes'
Order By
ProductName ASC
 
Table #2
 
SELECT ProductName, Price, '<a href="' + url + '">' + Title + '</a>' as Link
FROM ProductNames
WHERE Extn = '0151'
And url like 'http:%'
ORDER BY ProductName ASC
 
 


  I want to display all the data values taken from Table #1 as above.

View 3 Replies View Related

Syntax Error On LEFT JOIN

Mar 10, 2008

 HelloI am seeing the following syntax error: Error on Primary Select: Line 4: Incorrect syntax near '='.When I try to join two tables see my code below:------------------------------------------------------------------------------------------------------------------------ SELECT a.ProdName as [Product Name], b.price,b.link FROMProd_CatA a LEFT JOIN (SELECT ProdName, Price, '<a href="' + url + '">' + Title + '</a>' as Link FROM ProdNames WHERE = url like 'http:%' ) b  ON a.ProdName=b.ProdNameWhere a.Red = 'yes'ORDER BY a.ProdName ASC
------------------------------------------------------------------------------------------------------------------------------ I unable to find a solution.  I would be grateful if somebody could please advise.ThanksLynn  

View 3 Replies View Related

ANSI-92 Inner Join Vs. Where Clause Syntax

Jan 11, 2005

Having problems rewriting my join condition using the "inner join" syntax.

My query, working with an intersection table:

SELECT Description, EmailAddress
FROM Accounts_Roles r, Accounts_Users u, Accounts_UserRoles ur
WHERE
r.RoleID = ur.RoleID
AND
u.UserID = ur.UserID

This works fine, but i want to write it using 'inner join' style, so I tried:

SELECT Description, EmailAddress
FROM Accounts_Roles r, Accounts_Users u
INNER JOIN Accounts_UserRoles ur
ON
r.RoleID = ur.RoleID
AND
u.UserID = ur.UserID

which gives me an error (The column prefix 'r' does not match with a table name or alias name used in the query.)

Any ideas as to how I'm screwing this up would be appreciated.

Thanks,
Gordon Z

View 3 Replies View Related

SQL Server 2012 :: Syntax On A Join

Oct 23, 2015

What is wrong with my syntax?I want to return the value of the AchiveYear Value based on records in theCall that match.

SELECT DATEPART(yyyy,Call_Date) AS ArchiverYear
FROM tblCall
INNER JOIN PrismDataArchive.dbo.ArchiveDriver AS Arch ON tblCall.DATEPART(yyyy,Call_Date) = Arch.ArchiveYear

[code]...

View 9 Replies View Related

Outer Join Syntax Problem

Aug 24, 2006

Hi guys,

How can I translate this join into new syntax?

SELECT S.Dr_Code

FROM GJCSite S , GJCJob_Det JD, GJCSub_Job SJ

WHERE S.Com_Code = SJ.Com_Code (+)

AND JD.Sub_Job_Code = SJ.Sub_Job_Code (+)

AND JD.Job_Code = SJ.Job_Code (+)

Cheers,

View 5 Replies View Related

Help Me! Convert SQL Syntax To LINQ With Multi Join

May 5, 2008

Hi...
I have 3 tables:SportTeams (TeamID, TeamName)SportAthletes (TeamID, AthleteID, AthleteName)SportMedals (AthleteID, Medal)
I want to have a brief medal list (TeamID, G, S, B). I can write query in systax:
Select a.TeamID, a.TeamName_en,g.G,s.S,b.B from SportTeams aLeft Join(Select c.TeamID,Count(*) as G from SportMedals b Inner Join SportAthletes c On b.AthleteID = c.AthleteIDWhere Medal = 'G'Group By c.TeamID) g On a.TeamID = g.TeamIDLeft Join(Select c.TeamID,Count(*) as S from SportMedals b Inner Join SportAthletes c On b.AthleteID = c.AthleteIDWhere Medal = 'S'Group By c.TeamID) s On a.TeamID = s.TeamIDLeft Join(Select c.TeamID,Count(*) as B from SportMedals d Inner Join SportAthletes c On d.AthleteID = c.AthleteIDWhere Medal = 'B'Group By c.TeamID) b On a.TeamID = b.TeamIDOrder By g.G desc, s.S desc, b.B desc, a.TeamID asc
But I can't write it in LINQ syntax (I am beginner with C#, LINQ)
Can you help this sample to LINQ systax?
Thanks!

View 5 Replies View Related

Transact SQL :: Converting Old Outer Join Syntax

Aug 22, 2015

I'm a Power Builder (PB) developer. I've migrated PB from 10 .5 to 12.5, and now I need to migrate the stored procedures from SQL Server 2005 to 2012 as well.I get a invalid expression error when I run the procedures in Power Builder. We have previously been using a lower database compatibility model in 2005, which allowed the procedures to work there. I have learned that =* is the old way to write right outer joins.

                            For example:
                            select  *
                            from    A
                            right outer join
                                    B
                           
[code]...

Is my approach correct, or do I need to add a WHERE condition to it? I don't have access to the production database to check. The development database is in SQL Server 2012 too, sO I will not be able to run the old version there to check.

View 8 Replies View Related

Outer Join Syntax Problems (Multiple Tables)

Sep 13, 2005

Hello all--

I'm trying to run a SELECT on 3 tables: Class, Enrolled, Waiting.
I want to select the name of the class, the count of the students enrolled, and the count of the students waiting to enroll.

My current query...

SELECT     Class.Name, COUNT(Enrolled.StudentID) AS EnrolledCount, COUNT(Waiting.StudentID) AS WaitingCount
FROM         Class LEFT OUTER JOIN
                     
Enrolled ON Class.ClassID = Enrolled.ClassID LEFT OUTER JOIN
                     
Waiting ON Class.ClassID = Waiting.ClassID
GROUP BY Class.Name

...results in identical counts for enrolled and waiting, which I know
to be incorrect. Furthermore, it appears that the counts are being
multiplied together (in one instance, enrolled should be 14, waiting
should be 2, but both numbers come back as 28).

If I run this query without one of the joined tables, the counts are
accurate. The problem only occurs when I try to pull counts from both
the tables.

Can anyone find the problem with my query? Should I be using something other than a LEFT OUTER JOIN?

Thanks very much for your time,
--Jeremy

View 2 Replies View Related

Incorrect Syntax In User-defined Function

Sep 2, 2005

In the script below is the DDL to create some tables and a UDF.What I'm interested in is the UDF at the end. Specifically, these fewlines:--CLOSE OTRate--DEALLOCATE OTRateELSE-- @NumRecords <= 0If I uncommment CLOSE and DEALLOCATE and check the syntax I get amessage:"Incorrect syntax near keyword ELSE"Being a good little footsoldier, I want to release resourcesexplicitly, but clearly I'm putting the CLOSE and DEALLOCATE statementsin the wrong place.Could someone please tell me where I ought to put them so that thecursor is CLOSEd and DEALLOCATEd correctly.By the way, I am not after negative comments on the data design, or thelogic (or lack of it) in the function, just why the syntax erroroccurs.Thanks as everEdwardif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[Employee]') and OBJECTPROPERTY(id, N'IsUserTable') =1)drop table [dbo].[Employee]GOif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[PurchaseOrder]') and OBJECTPROPERTY(id,N'IsUserTable') = 1)drop table [dbo].[PurchaseOrder]GOif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[TimesheetItem]') and OBJECTPROPERTY(id,N'IsUserTable') = 1)drop table [dbo].[TimesheetItem]GOif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[Work]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[Work]GOif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[WorkOTRate]') and OBJECTPROPERTY(id, N'IsUserTable')= 1)drop table [dbo].[WorkOTRate]GOif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[WorkOTRateDefaults]') and OBJECTPROPERTY(id,N'IsUserTable') = 1)drop table [dbo].[WorkOTRateDefaults]GOCREATE TABLE [dbo].[Employee] ([EmployeeID] [int] IDENTITY (1, 1) NOT NULL ,[UserName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Title] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[FirstName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Surname] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,[DepartmentID] [int] NOT NULL ,[JobDescription] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_ASNULL ,[StartDate] [smalldatetime] NOT NULL ,[EndDate] [smalldatetime] NULL ,[DefaultRatePerHour] [smallmoney] NULL ,[EmailAddress] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_ASNULL ,[UserGroupID] [int] NOT NULL ,[Password] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[LastLogon] [datetime] NULL ,[PasswordChange] [smalldatetime] NULL ,[PreviousPassword1] [varchar] (50) COLLATESQL_Latin1_General_CP1_CI_AS NULL ,[PreviousPassword2] [varchar] (50) COLLATESQL_Latin1_General_CP1_CI_AS NULL ,[PreviousPassword3] [varchar] (50) COLLATESQL_Latin1_General_CP1_CI_AS NULL ,[PreviousPassword4] [varchar] (50) COLLATESQL_Latin1_General_CP1_CI_AS NULL ,[PreviousPassword5] [varchar] (50) COLLATESQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[PurchaseOrder] ([WorkOrderID] [int] IDENTITY (1, 1) NOT NULL ,[WorkID] [int] NOT NULL ,[OrderNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,[OrderDate] [datetime] NOT NULL ,[OrderValue] [money] NOT NULL ,[FixedPrice] [bit] NOT NULL ,[Prepaid] [bit] NOT NULL ,[AllocatedHours] [int] NULL ,[RatePerHour] [money] NULL ,[Summary] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Notes] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[TimesheetItem] ([ItemID] [int] IDENTITY (1, 1) NOT NULL ,[EmployeeID] [int] NOT NULL ,[TypeID] [int] NOT NULL ,[Start] [smalldatetime] NOT NULL ,[DurationMins] [int] NOT NULL ,[WorkID] [int] NULL ,[WorkComponentID] [int] NULL ,[WorkItemID] [int] NULL ,[Notes] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[OffSite] [tinyint] NULL ,[TravelTo] [smalldatetime] NULL ,[TravelToMins] [int] NULL ,[TravelFrom] [smalldatetime] NULL ,[TravelFromMins] [int] NULL ,[TravelMileage] [int] NULL ,[NonChargeableMins] [int] NULL ,[OTAuthorisedID] [int] NULL ,[OTAuthorisedDate] [smalldatetime] NULL ,[Abroad] [bit] NULL ,[InconvAllowance] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[ApprovalID] [int] NULL ,[AprovalDate] [smalldatetime] NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[Work] ([WorkID] [int] IDENTITY (1, 1) NOT NULL ,[WorkTypeID] [int] NULL ,[WorkCode] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Summary] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,[Notes] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Chargeable] [bit] NOT NULL ,[Complete] [bit] NOT NULL ,[ClientID] [int] NULL ,[ClientContactID] [int] NULL ,[Entered] [smalldatetime] NULL ,[ApprovalRequired] [tinyint] NULL ,[ColorCode] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[WorkOTRate] ([WorkOTRateID] [int] IDENTITY (1, 1) NOT NULL ,[WorkID] [int] NOT NULL ,[WorkDay] [int] NOT NULL ,[TimeFrom] [datetime] NOT NULL ,[TimeTo] [datetime] NOT NULL ,[RateMultiplier] [float] NOT NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[WorkOTRateDefaults] ([PKID] [int] IDENTITY (1, 1) NOT NULL ,[WorkDay] [int] NOT NULL ,[TimeFrom] [datetime] NULL ,[TimeTo] [datetime] NULL ,[RateMultiplier] [float] NOT NULL) ON [PRIMARY]GOSET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS OFFGO/*Function to determine the actual cost, in minutes, of a particularsegment of work. This is what it does, or is supposed to do.1. From the PARAMETER WorkID, determine the conclusion of the workblock associated with the TimesheetID - i.e. StartTime + DurationMins2. Establish whether there are records in the WorkOTRate tablecorresponding to this particular WorkID, weekday and time period3. If there are, get the amount of minutes by which the work blockcoincides.4. If there are no such records, get the default values from theWorkOTRateDefaults table5. If the block doesn't cross any boundaries then it's just regularwork, so just count the minutes.25/08/2005 EC*/CREATE FUNCTION fnGetWorkCostPerTimesheetItem(@TimesheetID int)RETURNS floatASBEGINDECLARE@OTRateTimeFrom datetime,@OTRateTimeTo as datetime,@OTRateMultiplier as float,@EndTime datetime,@ReturnValue as float,@OrderRatePerHour as money,@EmployeeRatePerHour as smallmoney,@NumRecords as int,@WorkID as int,@EmployeeID as int,@StartTime as smalldatetime,@Duration as int,@Found as int,@Chargeable as bit-- Get the various bits and bobs needed for the calculationSET @ReturnValue = 0SET @Found = 0SELECT@WorkID = WorkID,@EmployeeID = EmployeeID,@StartTime = Start,@Duration = DurationMinsFROMTimesheetItemWHEREItemID = @TimesheetID-- If this work is NOT chargeable, return 0SELECT@Chargeable = ChargeableFROM[Work]WHEREWorkID = @WorkIDIF @Chargeable = 1BEGINSET @EndTime = DATEADD(mi, @Duration, @StartTime)-- Get the rate per hour for this workSELECT@OrderRatePerHour = RatePerHourFROMPurchaseOrderWHEREWorkID = @WorkID-- Get the rate per hour for the employeeSELECT@EmployeeRatePerHour = DefaultRatePerHourFROMEmployeeWHERE(EmployeeID = @EmployeeID)-- Find out if there's an OT Rate set up for this WorkIDSELECT@NumRecords = Count(*)FROMWorkOTRateWHERE((WorkID = @WorkID) AND(WorkDay = DATEPART(dd, @StartTime)))IF @NumRecords > 0BEGINDECLARE OTRate CURSOR FORSELECTTimeFrom,TimeTo,RateMultiplierFROMWorkOTRateWHERE((WorkID = @WorkID) AND(WorkDay = DATEPART(dw, @StartTime)))OPEN OTRateFETCH NEXT FROM OTRate INTO @OTRateTimeFrom, @OTRateTimeTo,@OTRateMultiplierWHILE (@@fetch_status=0)BEGIN-- Set the two time values so that they match the date underconsideration.SET @OTRateTimeFrom = DATEADD(dd, DATEDIFF(dd, @OTRateTimeFrom,@StartTime) ,@OTRateTimeFrom)SET @OTRateTimeTo = DATEADD(dd, DATEDIFF(dd, @OTRateTimeTo ,@StartTime) ,@OTRateTimeTo)-- If the TimeTo part is < TimeFrom, then we know it crosses atime boundaryIF @OTRateTimeTo < @OTRateTimeFromSET @OTRateTimeTo = DATEADD(dd, 1, @OTRateTimeTo)-- If the time is between midnight and 8 a.m. it's the "next"dayIF CONVERT(datetime, @OTRateTimeFrom, 108) BETWEEN '00:00' AND'08:00'SET @OTRateTimeFrom = DATEADD(dd, 1, @OTRateTimeFrom)IF CONVERT(datetime, @OTRateTimeTo, 108) BETWEEN '00:00' AND'08:00'SET @OTRateTimeTo = DATEADD(dd, 1, @OTRateTimeTo)/*Ok, now we're in business. There are four possible scenariosthat we are interested in (ignoring when the Timesheet item period isentirely outside the OT rate period)NUMBER 1S EOT OTNUBMER 2S EOT OTNUMBER 3S EOT OTNUBMER 4S EOT OT*/-- NUMBER 1IF (@StartTime < @OTRateTimeFrom) AND (@EndTime > @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi,@OTRateTimeFrom, @OTRateTimeTo)) * @OTRateMultiplier))SET @Found = 1END--NUMBER 2ELSE IF (@StartTime < @OTRateTimeFrom) AND (@EndTime BETWEEN@OTRateTimeFrom AND @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi,@OTRateTimeFrom, @EndTime)) * @OTRateMultiplier))SET @Found = 1END-- NUMBER 3IF (@StartTime BETWEEN @OTRateTimeFrom AND @OTRateTimeTo) AND(@EndTime > @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi, @StartTime,@OTRateTimeTo)) * @OTRateMultiplier))SET @Found = 1END--NUMBER 4ELSE IF (@StartTime BETWEEN @OTRateTimeFrom AND @OTRateTimeTo)AND (@EndTime BETWEEN @OTRateTimeFrom AND @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi, @StartTime,@EndTime)) * @OTRateMultiplier))SET @Found = 1ENDFETCH NEXT FROM OTRate INTO @OTRateTimeFrom, @OTRateTimeTo,@OTRateMultiplierENDEND--CLOSE OTRate--DEALLOCATE OTRateELSE-- @NumRecords <= 0BEGINDECLARE OTRate CURSOR FORSELECTTimeFrom,TimeTo,RateMultiplierFROMWorkOTRateDefaultsWHERE(WorkDay = DATEPART(dw, @StartTime))OPEN OTRateFETCH NEXT FROM OTRate INTO @OTRateTimeFrom, @OTRateTimeTo,@OTRateMultiplierWHILE (@@fetch_status=0)BEGIN-- Set the two time values so that they match the date underconsideration.SET @OTRateTimeFrom = DATEADD(dd, DATEDIFF(dd, @OTRateTimeFrom,@StartTime) ,@OTRateTimeFrom)SET @OTRateTimeTo = DATEADD(dd, DATEDIFF(dd, @OTRateTimeTo ,@StartTime) ,@OTRateTimeTo)-- If the TimeTo part is < TimeFrom, then we know it crosses atime boundaryIF @OTRateTimeTo < @OTRateTimeFromSET @OTRateTimeTo = DATEADD(dd, 1, @OTRateTimeTo)-- If the time is between midnight and 8 a.m. it's the "next"dayIF CONVERT(datetime, @OTRateTimeFrom, 108) BETWEEN '00:00' AND'08:00'SET @OTRateTimeFrom = DATEADD(dd, 1, @OTRateTimeFrom)IF CONVERT(datetime, @OTRateTimeTo, 108) BETWEEN '00:00' AND'08:00'SET @OTRateTimeTo = DATEADD(dd, 1, @OTRateTimeTo)/*Ok, now we're in business. There are four possible scenariosthat we are interested in (ignoring when the Timesheet item period isentirely outside the OT rate period)NUMBER 1S EOT OTNUBMER 2S EOT OTNUMBER 3S EOT OTNUBMER 4S EOT OT*/-- NUMBER 1IF (@StartTime < @OTRateTimeFrom) AND (@EndTime > @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi,@OTRateTimeFrom, @OTRateTimeTo)) * @OTRateMultiplier))SET @Found = 1END--NUMBER 2ELSE IF (@StartTime < @OTRateTimeFrom) AND (@EndTime BETWEEN@OTRateTimeFrom AND @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi,@OTRateTimeFrom, @EndTime)) * @OTRateMultiplier))SET @Found = 1END-- NUMBER 3IF (@StartTime BETWEEN @OTRateTimeFrom AND @OTRateTimeTo) AND(@EndTime > @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi, @StartTime,@OTRateTimeTo)) * @OTRateMultiplier))SET @Found = 1END--NUMBER 4ELSE IF (@StartTime BETWEEN @OTRateTimeFrom AND @OTRateTimeTo)AND (@EndTime BETWEEN @OTRateTimeFrom AND @OTRateTimeTo)BEGINSET @ReturnValue = @ReturnValue + (((DATEDIFF(mi, @StartTime,@EndTime)) * @OTRateMultiplier))SET @Found = 1ENDFETCH NEXT FROM OTRate INTO @OTRateTimeFrom, @OTRateTimeTo,@OTRateMultiplierENDENDCLOSE OTRateDEALLOCATE OTRate-- If there were no matching OT records, it's just a regular blockof work in normal hoursIF @Found = 0SET @ReturnValue = @DurationEND-- Finally we factor in the relation between the Employee's rate andthe Order's stated rate.RETURN (@ReturnValue * (@EmployeeRatePerHour / @OrderRatePerHour))ENDGOSET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS ONGO

View 3 Replies View Related

Table Scalar Function Syntax. . How Wrong And How Far Am I?

Aug 3, 2006

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE FUNCTION DetailedView

AS

BEGIN

Declare @fieldname varchar(10)

Declare @stmt varchar(4000)

Declare Fields Cursor For Select Amounttype From Amounttypes

Set @stmt = 'Select pono, myid, billtype'

Open Fields

Fetch Next From Fields Into @fieldname

While @@Fetch_Status = 0 Begin

Set @stmt = @stmt + ', sum(amountfc * Case When amounttype = ''' + @fieldname + ''' Then 1 Else 0 End) As ' + @fieldname

Fetch Next From Fields Into @fieldname

End

Close Fields

Deallocate Fields

Set @stmt = @stmt + ' From multiplebillsviewall Group By pono, myId,billtype '

return Exec(@stmt)

END

View 3 Replies View Related

Syntax Error In Accessing An Object (table Value Function)

Aug 29, 2007

I am trying to access data from a database to print a report. The code I am using says I have a syntax error regarding the object person_info. Person_Info is a table value function on the SQL Server (2005). Does anybody see a problem with this line of code? Thanks for your help! Regards, Steve
 "INNER JOIN (SELECT * Person_Info FROM (" & Session("current_project") & ")) ON pc.personID_fk=pe.personID_pk " & _
 

View 4 Replies View Related

Join Using A Substring Function

Jul 30, 2007



Hi All,
I am trying to achieve loading a fact table using my stage and dimesion data , I was planning to use a Lookup transformation to do this, however I am supposed to use a substring task to because the data in the stage table is in adifferent format from that in the dimensions, how do I incorporate this substring task within the data flow, any help is appreciated.

Thanks

View 7 Replies View Related

Call Function For Inner Join

Aug 10, 2007



I have a procedure which has query
like Query 1.

Query 1

Select Clinetid
from clinet
inner join {


select centerid from GetChildCenter(@Centerid)
union
select centerid from getParentCenter(@Centerid)
} as Center c

on c.Centerid = client.Centerid


Query 2

declare @Center table ( centerid int)
insert into @Center

select centerid from getchildCenter(@Centerid) union all select centerid from getparentcenter(@Centerid)

Select Clinetid
from clinet
inner join @Center c on c.Centerid = client.Centerid





I just want to know which one is better performance wise..
because there is millions of rows for table center which is used by function getChildCenter() and GetparentCenter()

View 1 Replies View Related







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