Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Monday, March 26, 2012

Incorrect syntax near the keyword WHERE

Can someone help me? I am trying to script an SQL statement that would allow someone to INSERT a new username into a database where it is not a duplicate entry. The table is like this:
UserID - int, 4, identity(1,1)
UserName - nvarchar(50)
UserPass - nvarchar(50)

The code to execute this where i am getting the errors is this:


Function ChooseUName()
If Page.IsValid Then
Dim objCon As New SqlConnection(con)
Dim sqlInsert As String = "INSERT INTO tblUser (UserName) " & _
"VALUES (@.Username) WHERE NOT EXISTS (SELECT UserName FROM tblUser)"
Dim cmd As New SqlCommand(sqlInsert, objCon)
cmd.Parameters.Add("@.Username", SqlDbType.NVarChar, 50)
cmd.Parameters("@.Username").Value = txtUsername.Text

Dim id As Integer
Try
objCon.Open()
id = cmd.ExecuteScalar()
Finally
If objCon.State = ConnectionState.Open Then
objCon.Close()
End If
End Try

Response.Write("Your User ID is: " & id.ToString())
Response.End()
End If
End Function

This is the error:


Incorrect syntax near the keyword 'WHERE'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

Line 73: Try
Line 74: objCon.Open()
Line 75: id = cmd.ExecuteScalar()
Line 76: Finally
Line 77: If objCon.State = ConnectionState.Open Then

PLEASE HELP!! I'M ON A STRICT DEADLINE!!! :o THANKS IN ADVANCE!You need something more like this:


Dim sqlInsert As String = "IF NOT EXISTS (SELECT UserName FROM tblUser WHERE UserName=@.UserName) INSERT INTO tblUser (UserName) VALUES (@.Username)"

Terri|||THANK YOU SO VERY MUCH!!!

That worked like a charm. Do you or anyone else know of any resources online where i can learn more about using the SQL Syntax in my web apps? I've never seen such a string and now it's like a whole new world has opened up!

thanks again.|||You definitely need to haveSQL Server 2000 Books Online. This will help you tremendously with syntax issues. It's large but well worth the free download.

Another place you could look isMicrosoft ASP.NET Quickstarts Tutorial -- Server-Side Data Access. The section on "Inserting Data in a SQL Database" has coding to handle your situation, although they just do the INSERT and then test to see if it violated the primary key.

There are others out there, but those 2 resources come to mind first.

Terri

Incorrect syntax near the keyword 'Close'

When I created a SQL Server database by running a script, it gave me a
few errors like the following:
Incorrect syntax near the keyword 'KEY'.
Incorrect syntax near the keyword 'Close'.
Incorrect syntax near the keyword 'Open'.
Is this because those words (Key, CLose and Open) are reserved words ?
Thanks.We would definitely need to view the script in order to help you out here .
Could you post the script ?
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.com...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.|||Hi
Look at the subject "Reserved Keywords" in Books online all the words you
list are keywords. It is possible to use delimited identifiers if you want
to keep the keyword as an identifier see the topics
John
"Using Reserved Keywords" and "Delimited Identifiers" in Books online.
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.com...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.|||If you use keywords( documented in Books on line) as the names of ANY
objects in SQL you must brace them if
create table [OPEN]
([Key] int not null)
It is a good idea NOT to use reserve words if you can avoid it, because
you'll be forgetting to use the brackets and re-doing code over and
over(kind of annoying.)
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.com...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.|||To add to Wayne's response, you can also SET QUOTED_IDENTIFIER ON and
enclose identifiers in double quotes. This alternative to square brackets
is the ANSI-standard method. The best practice is to avoid reserved words,
though.
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE "OPEN"
("Key" int NOT NULL)
GO
--
Hope this helps.
Dan Guzman
SQL Server MVP
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.com...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.|||CREATE TABLE tblA (
Price varchar(50) NULL,
close varchar(50) NULL,
group1 varchar(50) NULL,
Cost varchar(50) NULL
)
go
CREATE TABLE tblB (
Product varchar(50) NULL,
open datetime NULL,
close datetime NULL
)
go
CREATE TABLE tblC (
key varchar(50) NULL,
First_name varchar(50) NULL
)
go
When I replaced "Close" to "Close1", "Open" to "Open1" and "key" to
"key1", the error did not appear anymore.
Thanks.
"Hassan" <fatima_ja@.hotmail.com> wrote in message news:<uEm9gM1oEHA.1900@.TK2MSFTNGP10.phx.gbl>...
> We would definitely need to view the script in order to help you out here .
> Could you post the script ?
> "fniles" <fiefieniles@.yahoo.com> wrote in message
> news:2067fd92.0409251452.60e065d7@.posting.google.com...
> > When I created a SQL Server database by running a script, it gave me a
> > few errors like the following:
> >
> > Incorrect syntax near the keyword 'KEY'.
> > Incorrect syntax near the keyword 'Close'.
> > Incorrect syntax near the keyword 'Open'.
> >
> > Is this because those words (Key, CLose and Open) are reserved words ?
> >
> > Thanks.|||Thank you.
If I use square brackets or double quotes on the colum name, do I access
that column with the square brackets or double quotes also ?
For example:
create table tblA ( [open] varchar(50) )
When I want to select column [open], do I do the following sql statement:
select open from tblA
OR
select [open] from tblA ?
create table tblA ( "open" varchar(50) )
When I want to select column "open", do I do the following sql statement:
select "open" from tblA
OR
select "open" from tblA ?
Thank you very much.
"Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
news:OhJ6cs9oEHA.3728@.TK2MSFTNGP09.phx.gbl...
> To add to Wayne's response, you can also SET QUOTED_IDENTIFIER ON and
> enclose identifiers in double quotes. This alternative to square brackets
> is the ANSI-standard method. The best practice is to avoid reserved
words,
> though.
> SET QUOTED_IDENTIFIER ON
> GO
> CREATE TABLE "OPEN"
> ("Key" int NOT NULL)
> GO
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "fniles" <fiefieniles@.yahoo.com> wrote in message
> news:2067fd92.0409251452.60e065d7@.posting.google.com...
> > When I created a SQL Server database by running a script, it gave me a
> > few errors like the following:
> >
> > Incorrect syntax near the keyword 'KEY'.
> > Incorrect syntax near the keyword 'Close'.
> > Incorrect syntax near the keyword 'Open'.
> >
> > Is this because those words (Key, CLose and Open) are reserved words ?
> >
> > Thanks.
>|||Enclosures are required when you use a reserved word but it doesn't matter
whether you use square brackets or double quotes. You can mix both.
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Fie Fie Niles" <fniles@.wincitesystems.com> wrote in message
news:eHXDZNDpEHA.3728@.TK2MSFTNGP09.phx.gbl...
> Thank you.
> If I use square brackets or double quotes on the colum name, do I access
> that column with the square brackets or double quotes also ?
> For example:
> create table tblA ( [open] varchar(50) )
> When I want to select column [open], do I do the following sql statement:
> select open from tblA
> OR
> select [open] from tblA ?
> create table tblA ( "open" varchar(50) )
> When I want to select column "open", do I do the following sql statement:
> select "open" from tblA
> OR
> select "open" from tblA ?
> Thank you very much.
> "Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
> news:OhJ6cs9oEHA.3728@.TK2MSFTNGP09.phx.gbl...
>> To add to Wayne's response, you can also SET QUOTED_IDENTIFIER ON and
>> enclose identifiers in double quotes. This alternative to square
>> brackets
>> is the ANSI-standard method. The best practice is to avoid reserved
> words,
>> though.
>> SET QUOTED_IDENTIFIER ON
>> GO
>> CREATE TABLE "OPEN"
>> ("Key" int NOT NULL)
>> GO
>> --
>> Hope this helps.
>> Dan Guzman
>> SQL Server MVP
>> "fniles" <fiefieniles@.yahoo.com> wrote in message
>> news:2067fd92.0409251452.60e065d7@.posting.google.com...
>> > When I created a SQL Server database by running a script, it gave me a
>> > few errors like the following:
>> >
>> > Incorrect syntax near the keyword 'KEY'.
>> > Incorrect syntax near the keyword 'Close'.
>> > Incorrect syntax near the keyword 'Open'.
>> >
>> > Is this because those words (Key, CLose and Open) are reserved words ?
>> >
>> > Thanks.
>>
>

Incorrect syntax near the keyword 'Close'

When I created a SQL Server database by running a script, it gave me a
few errors like the following:
Incorrect syntax near the keyword 'KEY'.
Incorrect syntax near the keyword 'Close'.
Incorrect syntax near the keyword 'Open'.
Is this because those words (Key, CLose and Open) are reserved words ?
Thanks.
We would definitely need to view the script in order to help you out here .
Could you post the script ?
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.c om...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.
|||Hi
Look at the subject "Reserved Keywords" in Books online all the words you
list are keywords. It is possible to use delimited identifiers if you want
to keep the keyword as an identifier see the topics
John
"Using Reserved Keywords" and "Delimited Identifiers" in Books online.
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.c om...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.
|||If you use keywords( documented in Books on line) as the names of ANY
objects in SQL you must brace them if
create table [OPEN]
([Key] int not null)
It is a good idea NOT to use reserve words if you can avoid it, because
you'll be forgetting to use the brackets and re-doing code over and
over(kind of annoying.)
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.c om...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.
|||To add to Wayne's response, you can also SET QUOTED_IDENTIFIER ON and
enclose identifiers in double quotes. This alternative to square brackets
is the ANSI-standard method. The best practice is to avoid reserved words,
though.
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE "OPEN"
("Key" int NOT NULL)
GO
Hope this helps.
Dan Guzman
SQL Server MVP
"fniles" <fiefieniles@.yahoo.com> wrote in message
news:2067fd92.0409251452.60e065d7@.posting.google.c om...
> When I created a SQL Server database by running a script, it gave me a
> few errors like the following:
> Incorrect syntax near the keyword 'KEY'.
> Incorrect syntax near the keyword 'Close'.
> Incorrect syntax near the keyword 'Open'.
> Is this because those words (Key, CLose and Open) are reserved words ?
> Thanks.
|||Thank you.
If I use square brackets or double quotes on the colum name, do I access
that column with the square brackets or double quotes also ?
For example:
create table tblA ( [open] varchar(50) )
When I want to select column [open], do I do the following sql statement:
select open from tblA
OR
select [open] from tblA ?
create table tblA ( "open" varchar(50) )
When I want to select column "open", do I do the following sql statement:
select "open" from tblA
OR
select "open" from tblA ?
Thank you very much.
"Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
news:OhJ6cs9oEHA.3728@.TK2MSFTNGP09.phx.gbl...
> To add to Wayne's response, you can also SET QUOTED_IDENTIFIER ON and
> enclose identifiers in double quotes. This alternative to square brackets
> is the ANSI-standard method. The best practice is to avoid reserved
words,
> though.
> SET QUOTED_IDENTIFIER ON
> GO
> CREATE TABLE "OPEN"
> ("Key" int NOT NULL)
> GO
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "fniles" <fiefieniles@.yahoo.com> wrote in message
> news:2067fd92.0409251452.60e065d7@.posting.google.c om...
>
|||Enclosures are required when you use a reserved word but it doesn't matter
whether you use square brackets or double quotes. You can mix both.
Hope this helps.
Dan Guzman
SQL Server MVP
"Fie Fie Niles" <fniles@.wincitesystems.com> wrote in message
news:eHXDZNDpEHA.3728@.TK2MSFTNGP09.phx.gbl...
> Thank you.
> If I use square brackets or double quotes on the colum name, do I access
> that column with the square brackets or double quotes also ?
> For example:
> create table tblA ( [open] varchar(50) )
> When I want to select column [open], do I do the following sql statement:
> select open from tblA
> OR
> select [open] from tblA ?
> create table tblA ( "open" varchar(50) )
> When I want to select column "open", do I do the following sql statement:
> select "open" from tblA
> OR
> select "open" from tblA ?
> Thank you very much.
> "Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
> news:OhJ6cs9oEHA.3728@.TK2MSFTNGP09.phx.gbl...
> words,
>

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

Friday, February 24, 2012

Include Comments in SQL Script

Hi,

When I generate SQL Script for my database, I wish to include the comments added against each column in the script. But there is no option available where I can specify to include "COMMENTS".

Please suggest.

Regards,

Sudhir Chawla

you can add custom comments by using this

-- two dashes

sql server scripts genarator has no comments option

you have to comment the scripts by yourself

|||

Or you can wrap your scripts in block comments

/*
If you have multiple
lines to comment
then you can use block comments
*/

|||

Actually,

When you create table and add columns, at that time there is a "DESCRIPTION" field, where we can specify the comments for that column. So how do I include these column level comments to be present in my script. I can add my own comments using -- or /* adjkasjd */, but I wish to include column level comments in my script.

Thanks for your advice.

Regards,

Sudhir

|||

I believe the DESCRIPTION field is actually an extended property. If you are using the Script Wizard (right click on the database, select check Tasks > Generate Scripts) to create your scripts, you can check the "Script Extended Properties" checkbox on the Script Options page to get the description scripted.

If you are using the Script context menu in Object Explorer to create your script, you will have to wait until SP2 to get this option, which will be exposed in a new scripting options dialog (e.g. Tools > Options > Scripting in the main menu bar).

Hope this helps,
Steve

Sunday, February 19, 2012

In the server explorer "generate create script" is greyed out, whats wrong?

In the server explorer "generate create script" is greyed out, what am I doing wrong?
I want to generate a script that will re-create my DB schema on another machine.
Any help would be appreciated.
ThanksFirst of all you have to use the proper names otherwise we dont know what you want. "enterprise manager no server explorer"

ok that was my anal retentive dba!!!
now

Books online {Documenting and Scripting Databases}

at the bottom of this doc are instructions on how to do it.|||First of all you have to use the proper names otherwise we dont know what you want. "enterprise manager no server explorer"

ok that was my anal retentive dba!!!
now

Books online {Documenting and Scripting Databases}

at the bottom of this doc are instructions on how to do it.

Ill be more clear, Im Using visual studio 2003, In my server explorer window, when I right click on my DB the "generate create script" option is greyed out. I would like to know why its greyed out?
Im guessing by your answer that this faeture is only available on "enterprise manager" edition? Can someone please confirm this for me?
Thankyou|||first of all sorry i thought that you were in the SQL tool directly , it didnt occur to me that you were in VS7

nope, object scripting is a feature that is avilable in every version of SQL Server. this might be a specific trait of VS7 and i dont currently have it installed anywhere to check.
sorry

RDjabarov can help here, he uses VS7