Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Wednesday, March 28, 2012

Incorrect week number with DATENAME in localized query

Hi,

I'm trying to use the DATENAME function to get a correct Dutch week number, but the DATENAME function seems not to return a localized week number. This is how I have tested it:

-- Set language to English
SET LANGUAGE us_English

-- Declare to dates 12/30/2006 and 12/31/2006
DECLARE @.Dec30 AS DATETIME SET @.Dec30 = CONVERT(DateTime, '2006-12-30')
DECLARE @.Dec31 AS DATETIME SET @.Dec31 = CONVERT(DateTime, '2006-12-31')

-- Return information about the declared dates in English
SELECT @.Dec30 as date1, DATENAME(week, @.Dec30) as week1, DATENAME(weekday, @.Dec30) as day1,
@.Dec31 as date2, DATENAME(week, @.Dec31) as week2, DATENAME(weekday, @.Dec31) as day2

-- Set language to Dutch
SET LANGUAGE Dutch

-- Return information about the declared dates in Dutch
SELECT @.Dec30 as date1, DATENAME(week, @.Dec30) as week1, DATENAME(weekday, @.Dec30) as day1,
@.Dec31 as date2, DATENAME(week, @.Dec31) as week2, DATENAME(weekday, @.Dec31) as day2

In both the English and Dutch results Saturday (12/30/2006) has week number 52 and Sunday (12/31/2006) has week number 53, but this is incorrect for the Dutch language. Sunday should also have week number 52, because the week starts on Monday in The Netherlands.

What am I doing wrong here and how can I get the correct localized week numbers from SQL Server? (I'm using SQL Server 2000 + SP4)

Thanks in advance.

SET Language is used configure the following options, DateFormat, DateFirst, Names of the Month & Names of the Days. So your in the rite direction to get your result..

BUT,

Unfortuantlly SQL Server won't help you to get the proper Week Number. Bcs they are not following ISO standard as you think. The Week 1 always = 1 - jan -any year. So sometimes you will get wrong week number.

The best approach to get the week number is use the custom function to get the week number.

Create Function dbo.MyWeekNo(@.dateFirst int, @.DateValue as DateTime) Returns Int
As
Begin
Declare @.Date as Datetime
declare @.Date2 as Datetime
Declare @.Week as int
Select @.Date = Convert(Varchar,Year(@.DateValue)) + '-01-01', @.Date2=DateAdd(DD,-1,@.Date)

Select @.Week = Case When WeekNo=0 Then dbo.MyWeekNo(@.dateFirst,@.Date2) Else WeekNo End
From
(
Select
Case When DatePart(W,@.Date) >= @.dateFirst Then DatePart(WW,@.DateValue) -1
Else DatePart(WW,@.DateValue) End WeekNo
) as Weeks

Return @.Week;
End

|||

Hi ManiD,

Your function is very close to the function I'm using for years now:

CREATE FUNCTION dbo.DutchWeek(@.DATE AS DateTime) RETURNS Int AS
BEGIN
IF @.DATE IS NULL RETURN NULL;

DECLARE @.JANFIRST AS DateTime
DECLARE @.WEEKDAY AS Int
DECLARE @.DAY AS Int
DECLARE @.DAYOFYEAR AS Int
DECLARE @.WEEKNUMBER AS Int

-- Get Januari the first of the year of @.DATE
SET @.JANFIRST = CONVERT(datetime, '1/1/' + CONVERT(varchar, YEAR(@.DATE)))

-- Calculate the number of the day where 0 = Monday, 1 = Tuesday, etc...
SET @.WEEKDAY = CONVERT(Int, @.JANFIRST) % 7

-- Calculate the (zero-bases) day number (0..265)
SET @.DAYOFYEAR = CONVERT(integer, @.DATE - @.JANFIRST)
-- Calculate the dutch week number
SET @.WEEKNUMBER = (@.DAYOFYEAR + @.WEEKDAY) / 7 +
CASE WHEN @.WEEKDAY > 3 THEN 0 ELSE 1 END

-- When week number is 0, get the weeknumber of the last week of the
-- previous year
IF @.WEEKNUMBER = 0
SET @.WEEKNUMBER = dbo.DutchWeek('12/31/' +
CONVERT(varchar, YEAR(@.DATE)-1));
RETURN @.WEEKNUMBER;
END

I use this function for years, but always had the feeling SQL Server should do this for me. But this is not the case, is it?

Incorrect syntax when there appears to be no syntax errors.

I keep receiving the following error whenever I try and call this function to update my database.

The code was working before, all I added was an extra field to update.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'

Public Sub MasterList_Update(sender As Object, e As DataListCommandEventArgs)

Dim strProjectName, txtProjectDescription, intProjectID, strProjectState as String
Dim intEstDuration, dtmCreationDate, strCreatedBy, strProjectLead, dtmEstCompletionDate as String

strProjectName = CType(e.Item.FindControl("txtProjectName"), TextBox).Text
txtProjectDescription = CType(e.Item.FindControl("txtProjDesc"), TextBox).Text
strProjectState = CType(e.Item.FindControl("txtStatus"), TextBox).Text
intEstDuration = CType(e.Item.FindControl("txtDuration"), TextBox).Text
dtmCreationDate = CType(e.Item.FindControl("txtCreation"),TextBox).Text
strCreatedBy = CType(e.Item.FindControl("txtCreatedBy"),TextBox).Text
strProjectLead = CType(e.Item.FindControl("txtLead"),TextBox).Text
dtmEstCompletionDate = CType(e.Item.FindControl("txtComDate"),TextBox).Text
intProjectID = CType(e.Item.FindControl("lblProjectID"), Label).Text

Dim strSQL As String
strSQL = "Update tblProject " _
& "Set strProjectName = @.strProjectName, " _
& "txtProjectDescription = @.txtProjectDescription, " _
& "strProjectState = @.strProjectState, " _
& "intEstDuration = @.intEstDuration, " _
& "dtmCreationDate = @.dtmCreationDate, " _
& "strCreatedBy = @.strCreatedBy, " _
& "strProjectLead = @.strProjectLead, " _
& "dtmEstCompletionDate = @.dtmEstCompletionDate, " _
& "WHERE intProjectID = @.intProjectID"

Dim myConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionstring"))
Dim cmdSQL As New SqlCommand(strSQL, myConnection)

cmdSQL.Parameters.Add(new SqlParameter("@.strProjectName", SqlDbType.NVarChar, 40))
cmdSQL.Parameters("@.strProjectName").Value = strProjectName
cmdSQL.Parameters.Add(new SqlParameter("@.txtProjectDescription", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@.txtProjectDescription").Value = txtProjectDescription
cmdSQL.Parameters.Add(new SqlParameter("@.strProjectState", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@.strProjectState").Value = strProjectState
cmdSQL.Parameters.Add(new SqlParameter("@.intEstDuration", SqlDbType.NVarChar, 60))
cmdSQL.Parameters("@.intEstDuration").Value = intEstDuration
cmdSQL.Parameters.Add(new SqlParameter("@.dtmCreationDate", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@.dtmCreationDate").Value = dtmCreationDate
cmdSQL.Parameters.Add(new SqlParameter("@.strCreatedBy", SqlDbType.NVarChar, 10))
cmdSQL.Parameters("@.strCreatedBy").Value = strCreatedBy
cmdSQL.Parameters.Add(new SqlParameter("@.strProjectLead", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@.strProjectLead").Value = strProjectLead
cmdSQL.Parameters.Add(new SqlParameter("@.dtmEstCompletionDate", SqlDbType.NVarChar, 24))
cmdSQL.Parameters("@.dtmEstCompletionDate").Value = dtmEstCompletionDate
cmdSQL.Parameters.Add(new SqlParameter("@.intProjectID", SqlDbType.NChar, 5))
cmdSQL.Parameters("@.intProjectID").Value = intProjectID

myConnection.Open()
cmdSQL.ExecuteNonQuery
myConnection.Close()

MasterList.EditItemIndex = -1
BindMasterList()

End Sub

Thankyou in advance.> cmdSQL.Parameters.Add(new SqlParameter("@.intProjectID", SqlDbType.NChar, 5))

why wouldintProjectID be an NChar? or is that just misleading?|||You have an extra comma.

"dtmEstCompletionDate = @.dtmEstCompletionDate, " _
"WHERE ... "

that would result in:

dtmEstCompletionDate = '1/1/2003', WHERE

there's an extra comma before the WHERE clause. That is causing the syntax error.

Cheers
Ken|||Good one!sql

Monday, March 26, 2012

Incorrect syntax near the keyword IF

I am writing a user defined function and I get the Error 156: Incorrect
syntax near the keyword IF. My function looks like this
CREATE FUNCTION dbo.func1(@.var1 varchar(64))
RETURNS @.MaintCost TABLE (@.result1 varchar(64), @.result2 varchar(64),
@.result3 varchar(64))
AS
IF @.var1 = 'I'
BEGIN
INSERT @.MaintCost
SELECT Col1, Col2, Col3
FROM tbl1
WHERE Col3 = 'I'
RETURN
END
ELSE
BEGIN
INSERT @.MaintCost
SELECT Col1, Col2, Col3
FROM tbl1
WHERE Col3 <> 'I'
RETURN
Thanks for the Help
ENDCREATE FUNCTION dbo.func1(@.var1 varchar(64))
RETURNS @.MaintCost TABLE (@.result1 varchar(64), @.result2 varchar(64),
@.result3 varchar(64))
AS
BEGIN
...
END
AMB
"Keith" wrote:

> I am writing a user defined function and I get the Error 156: Incorrect
> syntax near the keyword IF. My function looks like this
> CREATE FUNCTION dbo.func1(@.var1 varchar(64))
> RETURNS @.MaintCost TABLE (@.result1 varchar(64), @.result2 varchar(64),
> @.result3 varchar(64))
> AS
> IF @.var1 = 'I'
> BEGIN
> INSERT @.MaintCost
> SELECT Col1, Col2, Col3
> FROM tbl1
> WHERE Col3 = 'I'
> RETURN
> END
> ELSE
> BEGIN
> INSERT @.MaintCost
> SELECT Col1, Col2, Col3
> FROM tbl1
> WHERE Col3 <> 'I'
> RETURN
> Thanks for the Help
> END|||Try this:
CREATE FUNCTION dbo.func1(@.var1 varchar(64))
RETURNS @.MaintCost TABLE
(
result1 varchar(64),
result2 varchar(64),
result3 varchar(64)
)
AS
BEGIN
IF @.var1 = 'I'
BEGIN
INSERT @.MaintCost
SELECT Col1, Col2, Col3
FROM tbl1
WHERE Col3 = 'I'
END
ELSE
BEGIN
INSERT @.MaintCost
SELECT Col1, Col2, Col3
FROM tbl1
WHERE Col3 <> 'I'
END
RETURN
END

Incorrect syntax near keyword "function".

First a little history:
We have a Pentium II server running SQL 7.0. The SQL has a database that
our users connect to using a client front end app that was created by a
former programmer in our office. The file server name in the beginning was
called FRE3.
In the beginning the server was running NT4 and the users were on Win95
desktops.
We had a migration a few years ago where the server was upgraded to Windows
2000 server and the desktops were upgraded to Windows 2000 Professional. We
also had to make a server name change to fall in line with official naming
conventions. The server's name was changed to NTFRE. It was and still is
just a member server in our AD.
Of course, the client app had to be modified as it refers to the server name
and us non-programmers figured out how to change the name in the Visual Basic
code and recompiled a new executable and it worked fine. Just had to change
one instance in the code where it names the server.
We are now going through a new migration. We have a new box and have
installed Windows Server 2003 Enterprise on it. We have also installed SQL
2000 on it. Have updated all service packs and everything. Ran the copy
database wizard and successfully brought over the database from the SQL 7.0
server, as well as user logins. User destops are being migrated to Windows
XP as well.
So we broke into the code again, and changed the server name again like last
time, (new 2003 server is called S2K3-FRE-SQL1), and recompiled a new
executable.
Houston, we now have a problem. When I executed new executable on new XP
machine, I get this error message after logging in:
Run Time Error - '2147217900(80040e14)
Incorrect syntax near keyword 'function'
Does this error message mean anything to any of you gurus?
There is one bit of info that I need to relay, not sure if it matters or not:
The old server running 7.0, in Enterprise Manager, under SQL Server Group,
it states 2KFRE (Windows NT).
In the new server running 2000, in Enterprise Manager, under SQL Server
Group, it does not state the name of the server (S2K3-FRE-SQL1), it just
states Local (Windows NT).
Should I worry about this? Is the code looking for S2K3-FRE-SQL1 and seeing
the word Local instead, thus giving me my error message'?
Do you believe that the client code needs to be modified somewhere else now'
Is this error message a reflection of code built to address a SQL 7.0
installation and now it doesn't work as it's trying to talk to a SQL 2000
installation'Hi
function is a keyword so can't be used in the code. You may want to use the
scripting options of Enterprise Manager to script out the stored procedures
to try a textual search for function and see where it occurs. It could be
that you also have triggers which may contain the the key word. Alternatively
you could use SQL profiler to look at what SQL is being run on the server and
try and narrow down what is going on. If you want to look at
http://tinyurl.com/yejfye which is a MSDN webcast on using SQL 2000 Profiler,
there is also one for SQL 2005 and other tools.
You also have a lot of information in books online and it is certainly worth
your while browsing it.
HTH
John
"Rockitman" wrote:
> First a little history:
> We have a Pentium II server running SQL 7.0. The SQL has a database that
> our users connect to using a client front end app that was created by a
> former programmer in our office. The file server name in the beginning was
> called FRE3.
> In the beginning the server was running NT4 and the users were on Win95
> desktops.
> We had a migration a few years ago where the server was upgraded to Windows
> 2000 server and the desktops were upgraded to Windows 2000 Professional. We
> also had to make a server name change to fall in line with official naming
> conventions. The server's name was changed to NTFRE. It was and still is
> just a member server in our AD.
> Of course, the client app had to be modified as it refers to the server name
> and us non-programmers figured out how to change the name in the Visual Basic
> code and recompiled a new executable and it worked fine. Just had to change
> one instance in the code where it names the server.
> We are now going through a new migration. We have a new box and have
> installed Windows Server 2003 Enterprise on it. We have also installed SQL
> 2000 on it. Have updated all service packs and everything. Ran the copy
> database wizard and successfully brought over the database from the SQL 7.0
> server, as well as user logins. User destops are being migrated to Windows
> XP as well.
> So we broke into the code again, and changed the server name again like last
> time, (new 2003 server is called S2K3-FRE-SQL1), and recompiled a new
> executable.
> Houston, we now have a problem. When I executed new executable on new XP
> machine, I get this error message after logging in:
> Run Time Error - '2147217900(80040e14)
> Incorrect syntax near keyword 'function'
>
> Does this error message mean anything to any of you gurus?
> There is one bit of info that I need to relay, not sure if it matters or not:
> The old server running 7.0, in Enterprise Manager, under SQL Server Group,
> it states 2KFRE (Windows NT).
> In the new server running 2000, in Enterprise Manager, under SQL Server
> Group, it does not state the name of the server (S2K3-FRE-SQL1), it just
> states Local (Windows NT).
> Should I worry about this? Is the code looking for S2K3-FRE-SQL1 and seeing
> the word Local instead, thus giving me my error message'?
> Do you believe that the client code needs to be modified somewhere else now'
> Is this error message a reflection of code built to address a SQL 7.0
> installation and now it doesn't work as it's trying to talk to a SQL 2000
> installation'
>
>sql

Incorrect syntax near keyword "function".

First a little history:
We have a Pentium II server running SQL 7.0. The SQL has a database that
our users connect to using a client front end app that was created by a
former programmer in our office. The file server name in the beginning was
called FRE3.
In the beginning the server was running NT4 and the users were on Win95
desktops.
We had a migration a few years ago where the server was upgraded to Windows
2000 server and the desktops were upgraded to Windows 2000 Professional. W
e
also had to make a server name change to fall in line with official naming
conventions. The server's name was changed to NTFRE. It was and still is
just a member server in our AD.
Of course, the client app had to be modified as it refers to the server name
and us non-programmers figured out how to change the name in the Visual Basi
c
code and recompiled a new executable and it worked fine. Just had to change
one instance in the code where it names the server.
We are now going through a new migration. We have a new box and have
installed Windows Server 2003 Enterprise on it. We have also installed SQL
2000 on it. Have updated all service packs and everything. Ran the copy
database wizard and successfully brought over the database from the SQL 7.0
server, as well as user logins. User destops are being migrated to Windows
XP as well.
So we broke into the code again, and changed the server name again like last
time, (new 2003 server is called S2K3-FRE-SQL1), and recompiled a new
executable.
Houston, we now have a problem. When I executed new executable on new XP
machine, I get this error message after logging in:
Run Time Error - '2147217900(80040e14)
Incorrect syntax near keyword 'function'
Does this error message mean anything to any of you gurus?
There is one bit of info that I need to relay, not sure if it matters or not
:
The old server running 7.0, in Enterprise Manager, under SQL Server Group,
it states 2KFRE (Windows NT).
In the new server running 2000, in Enterprise Manager, under SQL Server
Group, it does not state the name of the server (S2K3-FRE-SQL1), it just
states Local (Windows NT).
Should I worry about this? Is the code looking for S2K3-FRE-SQL1 and seeing
the word Local instead, thus giving me my error message'?
Do you believe that the client code needs to be modified somewhere else now?
?
Is this error message a reflection of code built to address a SQL 7.0
installation and now it doesn't work as it's trying to talk to a SQL 2000
installation'Hi
function is a keyword so can't be used in the code. You may want to use the
scripting options of Enterprise Manager to script out the stored procedures
to try a textual search for function and see where it occurs. It could be
that you also have triggers which may contain the the key word. Alternativel
y
you could use SQL profiler to look at what SQL is being run on the server an
d
try and narrow down what is going on. If you want to look at
http://tinyurl.com/yejfye which is a MSDN webcast on using SQL 2000 Profiler
,
there is also one for SQL 2005 and other tools.
You also have a lot of information in books online and it is certainly worth
your while browsing it.
HTH
John
"Rockitman" wrote:

> First a little history:
> We have a Pentium II server running SQL 7.0. The SQL has a database that
> our users connect to using a client front end app that was created by a
> former programmer in our office. The file server name in the beginning wa
s
> called FRE3.
> In the beginning the server was running NT4 and the users were on Win95
> desktops.
> We had a migration a few years ago where the server was upgraded to Window
s
> 2000 server and the desktops were upgraded to Windows 2000 Professional.
We
> also had to make a server name change to fall in line with official naming
> conventions. The server's name was changed to NTFRE. It was and still i
s
> just a member server in our AD.
> Of course, the client app had to be modified as it refers to the server na
me
> and us non-programmers figured out how to change the name in the Visual Ba
sic
> code and recompiled a new executable and it worked fine. Just had to chan
ge
> one instance in the code where it names the server.
> We are now going through a new migration. We have a new box and have
> installed Windows Server 2003 Enterprise on it. We have also installed SQ
L
> 2000 on it. Have updated all service packs and everything. Ran the copy
> database wizard and successfully brought over the database from the SQL 7.
0
> server, as well as user logins. User destops are being migrated to Window
s
> XP as well.
> So we broke into the code again, and changed the server name again like la
st
> time, (new 2003 server is called S2K3-FRE-SQL1), and recompiled a new
> executable.
> Houston, we now have a problem. When I executed new executable on new XP
> machine, I get this error message after logging in:
> Run Time Error - '2147217900(80040e14)
> Incorrect syntax near keyword 'function'
>
> Does this error message mean anything to any of you gurus?
> There is one bit of info that I need to relay, not sure if it matters or n
ot:
> The old server running 7.0, in Enterprise Manager, under SQL Server Grou
p,
> it states 2KFRE (Windows NT).
> In the new server running 2000, in Enterprise Manager, under SQL Server
> Group, it does not state the name of the server (S2K3-FRE-SQL1), it just
> states Local (Windows NT).
> Should I worry about this? Is the code looking for S2K3-FRE-SQL1 and seei
ng
> the word Local instead, thus giving me my error message'?
> Do you believe that the client code needs to be modified somewhere else no
w'
> Is this error message a reflection of code built to address a SQL 7.0
> installation and now it doesn't work as it's trying to talk to a SQL 2000
> installation'
>
>

Friday, March 23, 2012

Incorrect syntax in user-defined function

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 few
lines:

--CLOSE OTRate
--DEALLOCATE OTRate
ELSE-- @.NumRecords <= 0

If I uncommment CLOSE and DEALLOCATE and check the syntax I get a
message:

"Incorrect syntax near keyword ELSE"

Being a good little footsoldier, I want to release resources
explicitly, but clearly I'm putting the CLOSE and DEALLOCATE statements
in the wrong place.

Could someone please tell me where I ought to put them so that the
cursor is CLOSEd and DEALLOCATEd correctly.

By the way, I am not after negative comments on the data design, or the
logic (or lack of it) in the function, just why the syntax error
occurs.

Thanks as ever

Edward

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Employee]') and OBJECTPROPERTY(id, N'IsUserTable') =
1)
drop table [dbo].[Employee]
GO

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[PurchaseOrder]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1)
drop table [dbo].[PurchaseOrder]
GO

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[TimesheetItem]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1)
drop table [dbo].[TimesheetItem]
GO

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Work]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Work]
GO

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[WorkOTRate]') and OBJECTPROPERTY(id, N'IsUserTable')
= 1)
drop table [dbo].[WorkOTRate]
GO

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[WorkOTRateDefaults]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1)
drop table [dbo].[WorkOTRateDefaults]
GO

CREATE TABLE [dbo].[Employee] (
[EmployeeID] [int] IDENTITY (1, 1) NOT NULL ,
[UserName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[Title] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FirstName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[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_AS
NULL ,
[StartDate] [smalldatetime] NOT NULL ,
[EndDate] [smalldatetime] NULL ,
[DefaultRatePerHour] [smallmoney] NULL ,
[EmailAddress] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[UserGroupID] [int] NOT NULL ,
[Password] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[LastLogon] [datetime] NULL ,
[PasswordChange] [smalldatetime] NULL ,
[PreviousPassword1] [varchar] (50) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL ,
[PreviousPassword2] [varchar] (50) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL ,
[PreviousPassword3] [varchar] (50) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL ,
[PreviousPassword4] [varchar] (50) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL ,
[PreviousPassword5] [varchar] (50) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

CREATE 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]
GO

CREATE 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]
GO

CREATE TABLE [dbo].[Work] (
[WorkID] [int] IDENTITY (1, 1) NOT NULL ,
[WorkTypeID] [int] NULL ,
[WorkCode] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[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]
GO

CREATE 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]
GO

CREATE 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]
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

/*
Function to determine the actual cost, in minutes, of a particular
segment of work. This is what it does, or is supposed to do.
1. From the PARAMETER WorkID, determine the conclusion of the work
block associated with the TimesheetID - i.e. StartTime + DurationMins
2. Establish whether there are records in the WorkOTRate table
corresponding to this particular WorkID, weekday and time period
3. If there are, get the amount of minutes by which the work block
coincides.
4. If there are no such records, get the default values from the
WorkOTRateDefaults table
5. If the block doesn't cross any boundaries then it's just regular
work, so just count the minutes.

25/08/2005 EC
*/

CREATE FUNCTION fnGetWorkCostPerTimesheetItem(@.TimesheetID int)

RETURNS float

AS

BEGIN

DECLARE

@.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 calculation
SET @.ReturnValue = 0
SET @.Found = 0

SELECT
@.WorkID = WorkID,
@.EmployeeID = EmployeeID,
@.StartTime = Start,
@.Duration = DurationMins
FROM
TimesheetItem
WHERE
ItemID = @.TimesheetID

-- If this work is NOT chargeable, return 0
SELECT
@.Chargeable = Chargeable
FROM
[Work]
WHERE
WorkID = @.WorkID

IF @.Chargeable = 1

BEGIN
SET @.EndTime = DATEADD(mi, @.Duration, @.StartTime)

-- Get the rate per hour for this work
SELECT
@.OrderRatePerHour = RatePerHour
FROM
PurchaseOrder
WHERE
WorkID = @.WorkID

-- Get the rate per hour for the employee
SELECT
@.EmployeeRatePerHour = DefaultRatePerHour
FROM
Employee
WHERE
(EmployeeID = @.EmployeeID)

-- Find out if there's an OT Rate set up for this WorkID
SELECT
@.NumRecords = Count(*)
FROM
WorkOTRate
WHERE
((WorkID = @.WorkID) AND
(WorkDay = DATEPART(dd, @.StartTime)))

IF @.NumRecords > 0
BEGIN

DECLARE OTRate CURSOR FOR
SELECT
TimeFrom,
TimeTo,
RateMultiplier
FROM
WorkOTRate
WHERE
((WorkID = @.WorkID) AND
(WorkDay = DATEPART(dw, @.StartTime)))

OPEN OTRate
FETCH NEXT FROM OTRate INTO @.OTRateTimeFrom, @.OTRateTimeTo,
@.OTRateMultiplier
WHILE (@.@.fetch_status=0)
BEGIN

-- Set the two time values so that they match the date under
consideration.
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 a
time boundary
IF @.OTRateTimeTo < @.OTRateTimeFrom
SET @.OTRateTimeTo = DATEADD(dd, 1, @.OTRateTimeTo)

-- If the time is between midnight and 8 a.m. it's the "next"
day
IF 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 scenarios
that we are interested in (ignoring when the Timesheet item period is
entirely outside the OT rate period)
NUMBER 1
S E
OT OT

NUBMER 2
S E
OT OT

NUMBER 3
S E
OT OT

NUBMER 4
S E
OT OT

*/
-- NUMBER 1
IF (@.StartTime < @.OTRateTimeFrom) AND (@.EndTime > @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi,
@.OTRateTimeFrom, @.OTRateTimeTo)) * @.OTRateMultiplier))
SET @.Found = 1
END
--NUMBER 2
ELSE IF (@.StartTime < @.OTRateTimeFrom) AND (@.EndTime BETWEEN
@.OTRateTimeFrom AND @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi,
@.OTRateTimeFrom, @.EndTime)) * @.OTRateMultiplier))
SET @.Found = 1
END
-- NUMBER 3
IF (@.StartTime BETWEEN @.OTRateTimeFrom AND @.OTRateTimeTo) AND
(@.EndTime > @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi, @.StartTime,
@.OTRateTimeTo)) * @.OTRateMultiplier))
SET @.Found = 1
END
--NUMBER 4
ELSE IF (@.StartTime BETWEEN @.OTRateTimeFrom AND @.OTRateTimeTo)
AND (@.EndTime BETWEEN @.OTRateTimeFrom AND @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi, @.StartTime,
@.EndTime)) * @.OTRateMultiplier))
SET @.Found = 1
END
FETCH NEXT FROM OTRate INTO @.OTRateTimeFrom, @.OTRateTimeTo,
@.OTRateMultiplier
END
END
--CLOSE OTRate
--DEALLOCATE OTRate
ELSE-- @.NumRecords <= 0

BEGIN
DECLARE OTRate CURSOR FOR
SELECT
TimeFrom,
TimeTo,
RateMultiplier
FROM
WorkOTRateDefaults
WHERE
(WorkDay = DATEPART(dw, @.StartTime))

OPEN OTRate
FETCH NEXT FROM OTRate INTO @.OTRateTimeFrom, @.OTRateTimeTo,
@.OTRateMultiplier

WHILE (@.@.fetch_status=0)
BEGIN

-- Set the two time values so that they match the date under
consideration.
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 a
time boundary
IF @.OTRateTimeTo < @.OTRateTimeFrom
SET @.OTRateTimeTo = DATEADD(dd, 1, @.OTRateTimeTo)

-- If the time is between midnight and 8 a.m. it's the "next"
day
IF 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 scenarios
that we are interested in (ignoring when the Timesheet item period is
entirely outside the OT rate period)
NUMBER 1
S E
OT OT

NUBMER 2
S E
OT OT

NUMBER 3
S E
OT OT

NUBMER 4
S E
OT OT
*/
-- NUMBER 1
IF (@.StartTime < @.OTRateTimeFrom) AND (@.EndTime > @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi,
@.OTRateTimeFrom, @.OTRateTimeTo)) * @.OTRateMultiplier))
SET @.Found = 1
END
--NUMBER 2
ELSE IF (@.StartTime < @.OTRateTimeFrom) AND (@.EndTime BETWEEN
@.OTRateTimeFrom AND @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi,
@.OTRateTimeFrom, @.EndTime)) * @.OTRateMultiplier))
SET @.Found = 1
END
-- NUMBER 3
IF (@.StartTime BETWEEN @.OTRateTimeFrom AND @.OTRateTimeTo) AND
(@.EndTime > @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi, @.StartTime,
@.OTRateTimeTo)) * @.OTRateMultiplier))
SET @.Found = 1
END
--NUMBER 4
ELSE IF (@.StartTime BETWEEN @.OTRateTimeFrom AND @.OTRateTimeTo)
AND (@.EndTime BETWEEN @.OTRateTimeFrom AND @.OTRateTimeTo)
BEGIN
SET @.ReturnValue = @.ReturnValue + (((DATEDIFF(mi, @.StartTime,
@.EndTime)) * @.OTRateMultiplier))
SET @.Found = 1
END

FETCH NEXT FROM OTRate INTO @.OTRateTimeFrom, @.OTRateTimeTo,
@.OTRateMultiplier
END
END
CLOSE OTRate
DEALLOCATE OTRate

-- If there were no matching OT records, it's just a regular block
of work in normal hours
IF @.Found = 0
SET @.ReturnValue = @.Duration
END

-- Finally we factor in the relation between the Employee's rate and
the Order's stated rate.
RETURN (@.ReturnValue * (@.EmployeeRatePerHour / @.OrderRatePerHour))
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GOteddysnips@.hotmail.com wrote:
> 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 few
> lines:
> --CLOSE OTRate
> --DEALLOCATE OTRate
> ELSE-- @.NumRecords <= 0
I haven't actually read the code through thoroughly, so I don't know if
others are going to give you advice about doing it in a set oriented
fashion, but I believe that your close and deallocate are coming one
END too late. The two ENDs above them (to my reading) are the END of
the while loop and then the end of the if statement. When using ELSE,
the following should be adhered to:

IF <condition>
<statement or block>
ELSE
<statement or block
where statement is either a single statement or:

BEGIN
<statement> [<statement>...]
END

Damien|||Damien wrote:
> teddysnips@.hotmail.com wrote:
> > 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 few
> > lines:
> > --CLOSE OTRate
> > --DEALLOCATE OTRate
> > ELSE-- @.NumRecords <= 0
> I haven't actually read the code through thoroughly, so I don't know if
> others are going to give you advice about doing it in a set oriented
> fashion, but I believe that your close and deallocate are coming one
> END too late.

You're quite right - many thanks! As for doing it using sets - well, I
really don't have time!

Edward|||(teddysnips@.hotmail.com) writes:
> You're quite right - many thanks! As for doing it using sets - well, I
> really don't have time!

But you assume that anyone will have the time to run that code? I hope
that you can find the time to test it on full-size data, before you
devote your important time to something else!

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Incorrect Syntax error?

I am getting the following error when attempting to call a certain function:

"Incorrect Syntax near spListPrograms, Line 1"

Here is the sproc:

ALTER PROCEDUREspListPrograms

@.parentIDint= 0

AS

SELECTpwbsID, pwbsTitleFROMProgramWBSWHEREpwbsParent = @.parentID

It is being called from this function:

PublicSharedFunction ListProgramChildNodes(OptionalByVal parentIDAsInteger = 0)As SqlDataReader

Dim cmdAsNew SqlCommand("spListPrograms", strConn)

cmd.Parameters.AddWithValue("@.parentID", parentID)

Try

strConn.Open()

Return cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch eAs SqlException

Dim errorMessagesAsString =""

Dim iAsInteger

For i = 0To e.Errors.Count - 1

errorMessages +="Index #" & i.ToString() & ControlChars.NewLine _

&"Message: " & e.Errors(i).Message & ControlChars.NewLine _

&"LineNumber: " & e.Errors(i).LineNumber & ControlChars.NewLine _

&"Source: " & e.Errors(i).Source & ControlChars.NewLine _

&"Procedure: " & e.Errors(i).Procedure & ControlChars.NewLine

Next i

MsgBox(errorMessages)

Finally

strConn.Close()

EndTry

EndFunction

The sproc works just fine when I execute it from the database directly in SQl Express. What could cause an incorrect syntax error? There's hardly any syntax there for an error to occur Thanks for any help you can give me.

Try specifying that the commandtype is a stored procedure and see if that takes care of your problem:
cmd.CommandType = CommandType.StoredProcedure
|||Thanks, I did finally figure that out after about 3 hours of pulling my hair out. Must need sleep or something...

Wednesday, March 21, 2012

Incorrect Subtotal in Matrix

Hi,

I am using the matrix element. in the data part i m using the aggregate function CountDistinct. and when i m taking the subtotal for this value across rows the total is coming wrong. while in the same matrix i have other data values also which uses functions SUM, for these the Subtotal is coming correct.

Can somebody tell me why this is happening with CountDistinct function.

Thanks in advance.

Count will count the number of occurrences of this record in a row or column. It will not add them together. Even if your value is more than 1, it will only count 1 time and add 1 to the total.
SUM adds the values in the rows together. That's why the subtotal will work correctly but CountDistinct not.

Hope this can help,
|||

Thanks for a quick response eduard,

what should i do to get the sum of all the rows where the countdistinct function is used?

|||Any work around on this?|||

the 'sum distinct' workaround might help

look for the whitepaper by 'fang wang' which has this sample in

Incorrect Subtotal in Matrix

Hi,

I am using the matrix element. in the data part i m using the aggregate function CountDistinct. and when i m taking the subtotal for this value across rows the total is coming wrong. while in the same matrix i have other data values also which uses functions SUM, for these the Subtotal is coming correct.

Can somebody tell me why this is happening with CountDistinct function.

Thanks in advance.

Count will count the number of occurrences of this record in a row or column. It will not add them together. Even if your value is more than 1, it will only count 1 time and add 1 to the total.
SUM adds the values in the rows together. That's why the subtotal will work correctly but CountDistinct not.

Hope this can help,
|||

Thanks for a quick response eduard,

what should i do to get the sum of all the rows where the countdistinct function is used?

|||Any work around on this?|||

the 'sum distinct' workaround might help

look for the whitepaper by 'fang wang' which has this sample in

sql

Monday, March 12, 2012

Inconsistent UDF column order

I have a UDF that when I run by two different users, gives two different
orders of data columns. One follows the syntax of the function and the othe
r
is mis-ordered but returns this way consistently. Has anyone else
encountered this?Can you post the ddl?
AMB
"ZachB" wrote:

> I have a UDF that when I run by two different users, gives two different
> orders of data columns. One follows the syntax of the function and the ot
her
> is mis-ordered but returns this way consistently. Has anyone else
> encountered this?|||Not sure what you mean by posting the ddl but here's the syntax of the UDF:
CREATE FUNCTION dbo. MISMOqryMINRegistrationCldDateNE(@.Enter_
Begin_Date
datetime,
@.Enter_End_Date datetime)
RETURNS TABLE
AS
RETURN ( SELECT TOP 100 PERCENT dbo.dbo_Tracking_File_Ext.f755#MERS,
dbo.MERS.MERS_MINNumber AS [MISMO MERS], dbo.tblLoanDetails.FirstSecond,
dbo.dbo_Tracking_File_Ext.f422#ClosingDate AS [MV Note
Date], dbo.tblLoanInfo.ClsdTDDate AS NoteDate,
dbo.LOAN_DETAILS.ClosingDate AS [MISMO ClosingDate],
dbo.tblLoanDetails.[Loan Amount],
dbo.LOAN_DETAILS.DisbursementDate AS [Funding Date],
dbo.dbo_Tracking_File_Ext.F251#CompanyName1,
dbo.dbo_Tracking_File_Ext.f252#CompanyName2,
dbo.GENERIC_ENTITY_LenderName._UnparsedName AS [MISMO CompanyName1],
' ' AS [MISMO CompanyName2],
dbo.qryBorrJoin.firstname, dbo.qryBorrJoin.B1MI, dbo.qryBorrJoin.Name AS
B1LastName, dbo.qryBorrJoin.BSSN,
dbo.qryBorrJoin.CoFirstName, dbo.qryBorrJoin.B2MI,
dbo.qryBorrJoin.coLastName, dbo.qryBorrJoin.CBSSN, dbo.tblLoanInfo.[Security
Address Street],
dbo.tblLoanInfo.City, dbo.tblLoanInfo.State,
dbo.tblLoanInfo.ZIP, dbo.dbo_Tracking_File.f555#property_county,
dbo.PROPERTY._County AS [MISMO property_county],
dbo.dbo_Tracking_File_Ext.f519#TrusteeName,
dbo.GENERIC_ENTITY_Trustee._UnparsedName AS [MISMO
TrusteeName], dbo.tblStateLookup.StateTrustVMort,
dbo.tblClosedLoan.LoanNumber,
dbo.[tblPurpose Lookup].PurpComerica,
dbo.tblClosedLoan.CommitID, dbo.tblClosedLoan.SandDYN,
dbo.tblClosedLoan.PSStatus
FROM dbo.tblStateLookup RIGHT OUTER JOIN
dbo.dbo_Tracking_File RIGHT OUTER JOIN
dbo.qryBorrJoin INNER JOIN
dbo.tblLoanInfo INNER JOIN
dbo.tblLoanDetails INNER JOIN
dbo.tblClosedLoan ON dbo.tblLoanDetails.LoanDetailID =
dbo.tblClosedLoan.NCLoanNumber ON
dbo.tblLoanInfo.[Acct Number] =
dbo.tblLoanDetails.[Loan Number] ON
dbo.qryBorrJoin.[Loan Number] = dbo.tblLoanInfo.[Acct
Number] LEFT OUTER JOIN
dbo.[tblPurpose Lookup] ON dbo.tblLoanInfo.Purpose =
dbo.[tblPurpose Lookup].[Purpose Lookup] LEFT OUTER JOIN
dbo.dbo_Tracking_File_Ext ON
dbo.tblClosedLoan.LoanNumber = dbo.dbo_Tracking_File_Ext.Loan_ID ON
dbo.dbo_Tracking_File.Loan_ID =
dbo.tblClosedLoan.LoanNumber ON dbo.tblStateLookup.StateID =
dbo.tblLoanInfo.State LEFT OUTER JOIN
dbo._CLOSING_DOCUMENTS LEFT OUTER JOIN
dbo.GENERIC_ENTITY_LenderName ON
dbo._CLOSING_DOCUMENTS.CLDC_ID = dbo.GENERIC_ENTITY_LenderName.CLDC_ID LEFT
OUTER JOIN
dbo.GENERIC_ENTITY_Trustee RIGHT OUTER JOIN
dbo.RECORDABLE_DOCUMENT ON
dbo.GENERIC_ENTITY_Trustee.RCDO_ID = dbo.RECORDABLE_DOCUMENT.RCDO_ID ON
dbo._CLOSING_DOCUMENTS.CLDC_ID =
dbo.RECORDABLE_DOCUMENT.CLDC_ID RIGHT OUTER JOIN
dbo.MORTGAGE_TERMS_MaxAppl LEFT OUTER JOIN
dbo.LOAN_APPLICATION ON
dbo.MORTGAGE_TERMS_MaxAppl.APPL_ID = dbo.LOAN_APPLICATION.APPL_ID LEFT OUTER
JOIN
dbo.PROPERTY ON dbo.MORTGAGE_TERMS_MaxAppl.APPL_ID =
dbo.PROPERTY.APPL_ID ON
dbo._CLOSING_DOCUMENTS.LOAN_ID =
dbo.LOAN_APPLICATION.LOAN_ID LEFT OUTER JOIN
dbo.LOAN_DETAILS ON dbo._CLOSING_DOCUMENTS.CLDC_ID =
dbo.LOAN_DETAILS.CLDC_ID LEFT OUTER JOIN
dbo.MERS ON dbo.MORTGAGE_TERMS_MaxAppl.APPL_ID =
dbo.MERS.APPL_ID ON
dbo.tblClosedLoan.LoanNumber =
dbo.MORTGAGE_TERMS_MaxAppl.LenderLoanIdentifier
WHERE (dbo.tblLoanInfo.ClsdTDDate BETWEEN @.Enter_Begin_Date AND
@.Enter_End_Date) AND (dbo.tblClosedLoan.SandDYN = 0 OR
dbo.tblClosedLoan.SandDYN IS NULL) AND
(dbo.tblClosedLoan.PSStatus <> N'rescinded')
ORDER BY dbo.qryBorrJoin.Name, dbo.qryBorrJoin.firstname )|||ZachB,
When you say "gives two different orders of data columns", Do you mean
different sort of the result or that the column list is different?. How are
you querying this table function?
The "order by" clause used inside the function does not guarantee any order
of the result when you use:
declare @.sd datetime
declare @.ed datetime
set @.sd = '20050101'
set @.ed = '20050321'
select col1, col2, ..., coln
from dbo.MISMOqryMINRegistrationCldDateNE(@.sd, @.ed) as t
you have to use an "order by" clause again if you want the order of the rows
to be consistent.
select col1, col2, ..., coln
from dbo.MISMOqryMINRegistrationCldDateNE(@.sd, @.ed) as t
order by col1, ...
AMB
"ZachB" wrote:

> Not sure what you mean by posting the ddl but here's the syntax of the UDF
:
> CREATE FUNCTION dbo. MISMOqryMINRegistrationCldDateNE(@.Enter_
Begin_Date
> datetime,
> @.Enter_End_Date datetime)
> RETURNS TABLE
> AS
> RETURN ( SELECT TOP 100 PERCENT dbo.dbo_Tracking_File_Ext.f755#MERS,
> dbo.MERS.MERS_MINNumber AS [MISMO MERS], dbo.tblLoanDetails.FirstSecond,
> dbo.dbo_Tracking_File_Ext.f422#ClosingDate AS [MV No
te
> Date], dbo.tblLoanInfo.ClsdTDDate AS NoteDate,
> dbo.LOAN_DETAILS.ClosingDate AS [MISMO ClosingDate],
> dbo.tblLoanDetails.[Loan Amount],
> dbo.LOAN_DETAILS.DisbursementDate AS [Funding Date],
> dbo.dbo_Tracking_File_Ext.F251#CompanyName1,
> dbo.dbo_Tracking_File_Ext.f252#CompanyName2,
> dbo.GENERIC_ENTITY_LenderName._UnparsedName AS [MISMO CompanyName1],
> ' ' AS [MISMO CompanyName2],
> dbo.qryBorrJoin.firstname, dbo.qryBorrJoin.B1MI, dbo.qryBorrJoin.Name AS
> B1LastName, dbo.qryBorrJoin.BSSN,
> dbo.qryBorrJoin.CoFirstName, dbo.qryBorrJoin.B2MI,
> dbo.qryBorrJoin.coLastName, dbo.qryBorrJoin.CBSSN, dbo.tblLoanInfo.[Securi
ty
> Address Street],
> dbo.tblLoanInfo.City, dbo.tblLoanInfo.State,
> dbo.tblLoanInfo.ZIP, dbo.dbo_Tracking_File.f555#property_county,
> dbo.PROPERTY._County AS [MISMO property_county],
> dbo.dbo_Tracking_File_Ext.f519#TrusteeName,
> dbo.GENERIC_ENTITY_Trustee._UnparsedName AS [MISMO
> TrusteeName], dbo.tblStateLookup.StateTrustVMort,
> dbo.tblClosedLoan.LoanNumber,
> dbo.[tblPurpose Lookup].PurpComerica,
> dbo.tblClosedLoan.CommitID, dbo.tblClosedLoan.SandDYN,
> dbo.tblClosedLoan.PSStatus
> FROM dbo.tblStateLookup RIGHT OUTER JOIN
> dbo.dbo_Tracking_File RIGHT OUTER JOIN
> dbo.qryBorrJoin INNER JOIN
> dbo.tblLoanInfo INNER JOIN
> dbo.tblLoanDetails INNER JOIN
> dbo.tblClosedLoan ON dbo.tblLoanDetails.LoanDetailID
=
> dbo.tblClosedLoan.NCLoanNumber ON
> dbo.tblLoanInfo.[Acct Number] =
> dbo.tblLoanDetails.[Loan Number] ON
> dbo.qryBorrJoin.[Loan Number] = dbo.tblLoanInfo.[Acc
t
> Number] LEFT OUTER JOIN
> dbo.[tblPurpose Lookup] ON dbo.tblLoanInfo.Purpose =
> dbo.[tblPurpose Lookup].[Purpose Lookup] LEFT OUTER JOIN
> dbo.dbo_Tracking_File_Ext ON
> dbo.tblClosedLoan.LoanNumber = dbo.dbo_Tracking_File_Ext.Loan_ID ON
> dbo.dbo_Tracking_File.Loan_ID =
> dbo.tblClosedLoan.LoanNumber ON dbo.tblStateLookup.StateID =
> dbo.tblLoanInfo.State LEFT OUTER JOIN
> dbo._CLOSING_DOCUMENTS LEFT OUTER JOIN
> dbo.GENERIC_ENTITY_LenderName ON
> dbo._CLOSING_DOCUMENTS.CLDC_ID = dbo.GENERIC_ENTITY_LenderName.CLDC_ID LEF
T
> OUTER JOIN
> dbo.GENERIC_ENTITY_Trustee RIGHT OUTER JOIN
> dbo.RECORDABLE_DOCUMENT ON
> dbo.GENERIC_ENTITY_Trustee.RCDO_ID = dbo.RECORDABLE_DOCUMENT.RCDO_ID ON
> dbo._CLOSING_DOCUMENTS.CLDC_ID =
> dbo.RECORDABLE_DOCUMENT.CLDC_ID RIGHT OUTER JOIN
> dbo.MORTGAGE_TERMS_MaxAppl LEFT OUTER JOIN
> dbo.LOAN_APPLICATION ON
> dbo.MORTGAGE_TERMS_MaxAppl.APPL_ID = dbo.LOAN_APPLICATION.APPL_ID LEFT OUT
ER
> JOIN
> dbo.PROPERTY ON dbo.MORTGAGE_TERMS_MaxAppl.APPL_ID =
> dbo.PROPERTY.APPL_ID ON
> dbo._CLOSING_DOCUMENTS.LOAN_ID =
> dbo.LOAN_APPLICATION.LOAN_ID LEFT OUTER JOIN
> dbo.LOAN_DETAILS ON dbo._CLOSING_DOCUMENTS.CLDC_ID =
> dbo.LOAN_DETAILS.CLDC_ID LEFT OUTER JOIN
> dbo.MERS ON dbo.MORTGAGE_TERMS_MaxAppl.APPL_ID =
> dbo.MERS.APPL_ID ON
> dbo.tblClosedLoan.LoanNumber =
> dbo.MORTGAGE_TERMS_MaxAppl.LenderLoanIdentifier
> WHERE (dbo.tblLoanInfo.ClsdTDDate BETWEEN @.Enter_Begin_Date AND
> @.Enter_End_Date) AND (dbo.tblClosedLoan.SandDYN = 0 OR
> dbo.tblClosedLoan.SandDYN IS NULL) AND
> (dbo.tblClosedLoan.PSStatus <> N'rescinded')
> ORDER BY dbo.qryBorrJoin.Name, dbo.qryBorrJoin.firstname )|||The UDF is being called from an MS Access .adp project. The "order" of the
data columns is different meaning in one case it shows Column A, Column B,
Column C, Column D but in the other it shows Column B, Column C, Column A,
Column D (Even if the syntax says SELECT Column A, Column B, Column C, Colum
n
D.
row 1 test1 test2 test3 test4
vs.
row 1 test2 test3 test1 test4
"Alejandro Mesa" wrote:
> ZachB,
> When you say "gives two different orders of data columns", Do you mean
> different sort of the result or that the column list is different?. How ar
e
> you querying this table function?
> The "order by" clause used inside the function does not guarantee any orde
r
> of the result when you use:
> declare @.sd datetime
> declare @.ed datetime
> set @.sd = '20050101'
> set @.ed = '20050321'
> select col1, col2, ..., coln
> from dbo.MISMOqryMINRegistrationCldDateNE(@.sd, @.ed) as t
> you have to use an "order by" clause again if you want the order of the ro
ws
> to be consistent.
> select col1, col2, ..., coln
> from dbo.MISMOqryMINRegistrationCldDateNE(@.sd, @.ed) as t
> order by col1, ...
>
> AMB
> "ZachB" wrote:
>|||ZachB,
Can you trace the statements sent to sql server by the project?
AMB
"ZachB" wrote:
> The UDF is being called from an MS Access .adp project. The "order" of th
e
> data columns is different meaning in one case it shows Column A, Column B,
> Column C, Column D but in the other it shows Column B, Column C, Column A,
> Column D (Even if the syntax says SELECT Column A, Column B, Column C, Col
umn
> D.
> row 1 test1 test2 test3 test4
> vs.
> row 1 test2 test3 test1 test4
> "Alejandro Mesa" wrote:
>|||Not that I'm aware of. I know you can check the properties of a particular
spid under Current Activity and see what syntax is or has just been run. Bu
t
I would assume that since the two users are hitting the same .adp they
shouldn't be passing different statements.
The MS Access .adp menu option states:
Open table 'dbo.MISMOqryMINRegistrationCldDateNE'
and this is just one example. This mis-ordering happens consisently across
several UDFs that I'm working with.
"Alejandro Mesa" wrote:

> ZachB,
> Can you trace the statements sent to sql server by the project?
>
> AMB|||Use Profiler to trace activities in the server. You can read about it in BOL
.
AMB
"ZachB" wrote:
> Not that I'm aware of. I know you can check the properties of a particula
r
> spid under Current Activity and see what syntax is or has just been run.
But
> I would assume that since the two users are hitting the same .adp they
> shouldn't be passing different statements.
> The MS Access .adp menu option states:
> Open table 'dbo.MISMOqryMINRegistrationCldDateNE'
> and this is just one example. This mis-ordering happens consisently acros
s
> several UDFs that I'm working with.
> "Alejandro Mesa" wrote:
>|||Anyone else? While I'm learning to trace, has anyone ever had a UDF return
data in different COLUMN order for different users? Let me know. Thanks i
n
advance.
"ZachB" wrote:

> I have a UDF that when I run by two different users, gives two different
> orders of data columns. One follows the syntax of the function and the ot
her
> is mis-ordered but returns this way consistently. Has anyone else
> encountered this?|||"ZachB" <ZachB@.discussions.microsoft.com> wrote in message
news:5966BAE6-5CC4-4055-A8D9-454B2E5A2E9C@.microsoft.com...
> Anyone else? While I'm learning to trace, has anyone ever had a UDF
return
> data in different COLUMN order for different users? Let me know. Thanks
in
> advance.
>
Wild Guesses:
1. The clients are executing different code. One client has been updated
and the other hasn't.
2. The clients are attached to different databases, one on test and one on
production.
3. It isn't really happening - The client preferences are different so that
on one client things appear differently but aren't actually different.
(e.g. hidden display controls, etc)
4. You are using Select * and there is a weird caching thing going on.
Good Luck.
Jim

Friday, March 9, 2012

Inconsistency in HTML display

Hi all i am currently using a custom aggregate function in the Stored Proc to Concatenate certain fields and group the others. The concatenation is done be leaving an empty line (Line Break) inbetween. The problem is that the New Line Break is getting displayed in the PDF format of the Reports generated using Reporting Service 2005 but in the HTML (using IE) format the Line break does not occur, can anyone help me out with this. Doesnt IE support New Line?

You can change the width of this line with specific property (lineheigt) on that TABLEROW object. You must complete the "write" expression on that property and the results are fine.

For example you can use the function posted below to get the number of occurence of char(13) character.

TABLEROW1.LineHeight= n*(1-occurs(@.yourstring,char(13))

Create function occurs

(

@.iStr varchar(4000),

@.fStr varchar(100)

)

Returns smallint As

Begin

Declare @.rStr varchar(100)

Select @.rStr = case when charindex(left(@.fStr,1),@.fStr,2)>0 then stuff(@.fStr,charindex(left(@.fStr,1),@.fStr,2),0,'~') else Replicate('~',datalength(@.fStr)+1) end

Return(datalength(Replace(Replace(@.iStr,@.fStr,@.rStr),@.fStr,@.rStr)) - datalength(@.iStr))

End

Friday, February 24, 2012

IN() and duplicates

Does it matter to SQL if the IN() function has duplicates?This generates the same execution plan
USE pubs
SELECT * FROM authors
WHERE au_id
IN('172-32-1176','172-32-1176','172-32-1176','172-32-1176','213-46-8915')
SELECT * FROM authors
WHERE au_id IN('172-32-1176','213-46-8915')
Denis the SQL Menace
http://sqlservercode.blogspot.com/
Jayyde wrote:
> Does it matter to SQL if the IN() function has duplicates?|||Thanks :). I'm sure it's inefficient, but I'm guessing less so for SQL than
for me to take the time for C# to check for the duplicates.
-Jayyde
"SQL Menace" <denis.gobo@.gmail.com> wrote in message
news:1149689506.053562.310900@.i40g2000cwc.googlegroups.com...
> This generates the same execution plan
> USE pubs
> SELECT * FROM authors
> WHERE au_id
> IN('172-32-1176','172-32-1176','172-32-1176','172-32-1176','213-46-8915')
> SELECT * FROM authors
> WHERE au_id IN('172-32-1176','213-46-8915')
> Denis the SQL Menace
> http://sqlservercode.blogspot.com/
>
> Jayyde wrote:
>|||Unless the list is huge, generally it shouldn't matter. IN() implies
distinct elements even for subqueries.
Anith