Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Friday, March 30, 2012

Help in Case statement

Hi,

I have to use case statement in where condition of a sql query. I get an error

Incorrect syntax near '<'.

Declare @.iPostingID int

set @.iPostingId = 1

Select PostingID from JobsDB_JobPostings where DateDiff(day,PostingDate,getdate())

case @.iPostingId

when 1 then '<1'

when 2 then '<7'

when 3 then '<30'

when 4 then '<60'

when 5 then '<90'

end

Can anyone help me please

Thanks,

Uma Ramiya

Hi,

Maybe you want this:

Code Snippet

SELECT

CASE PostingID

WHEN 1 THEN '<1'

WHEN 2 THEN '<7'

WHEN 3 THEN '<30'

WHEN 4 THEN '<60'

WHEN 5 THEN '<90'

END

FROM JobsDB_JobPostings WHERE DATEDIFF(DAY,PostingDate,GETDATE())

Regards,

Janos

|||The parameter @.iPostingId is used for comparison and not the column field.|||Well, you need the select before the CASE|||Hi,

We use similar construct in our daily life here. Have a look on following query, this will really work.

DECLARE @.iPostingID int

SET @.iPostingId = 1

SELECT
PostingID
FROM
JobsDB_JobPostings
WHERE
DateDiff(day,PostingDate,getdate()) < (CASE
WHEN @.iPostingId = 1 THEN 1
WHEN @.iPostingId = 2 THEN 7
WHEN @.iPostingId = 3 THEN 30
WHEN @.iPostingId = 4 THEN 60
WHEN @.iPostingId = 5 THEN 90
END)|||

Hi I have the following case.i would like a precise and efficient SQL Statement for it.

I have 7 parameters which are used for comparison. I need to run the query with these parameters. which ever is not null should be compared and the null ones should be ignored. AS a result I end with lots of "if' statements as the parameters form a lot of copmbination. Is there any way to cut short the code

ALTER PROCEDURE [dbo].[JobsDb_Resumes_SelectForMatchingSkills]

@.sSkill varchar(50),

@.iCountryID int=NULL,

@.iStateID int=NULL,

@.iJobTypeID int=NULL,

@.iMinSal int=NULL,

@.iMaxSal int NULL,

@.iPeriodPosted int NULL

AS

IF @.iCountryID!=NULL AND @.iStateID=NULL AND @.iJobTypeID = NULL and @.iMinSal = NULL and @.iMaxSal = Null and iPeriodPosted = NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

IF @.iCountryID!=NULL AND @.iStateID!=NULL AND @.iJobTypeID = NULL and @.iMinSal = NULL and @.iMaxSal = Null and iPeriodPosted = NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID AND

targetstateid=@.iStateID and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

IF @.iCountryID!=NULL AND @.iStateID!=NULL AND @.iJobTypeID != NULL and @.iMinSal = NULL and @.iMaxSal = Null and iPeriodPosted = NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID AND

targetstateid=@.iStateID and

jobtypeid=@.iJobTypeID and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

IF @.iCountryID!=NULL AND @.iStateID!=NULL AND @.iJobTypeID != NULL and @.iMinSal != NULL and @.iMaxSal = Null and iPeriodPosted = NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID AND

targetstateid=@.iStateID and

jobtypeid=@.iJobTypeID and

minsalary >= @.iminsal and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

IF @.iCountryID!=NULL AND @.iStateID!=NULL AND @.iJobTypeID != NULL and @.iMinSal != NULL and @.iMaxSal != Null and iPeriodPosted = NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID AND

targetstateid=@.iStateID and

jobtypeid=@.iJobTypeID and

minsalary >= @.iminsal and

maxsalary >= @.imaxsal and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

IF @.iCountryID!=NULL AND @.iStateID!=NULL AND @.iJobTypeID != NULL and @.iMinSal != NULL and @.iMaxSal != Null and iPeriodPosted = NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID AND

targetstateid=@.iStateID and

jobtypeid=@.iJobTypeID and

minsalary >= @.iminsal and

maxsalary >= @.imaxsal and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

IF @.iCountryID!=NULL AND @.iStateID!=NULL AND @.iJobTypeID != NULL and @.iMinSal != NULL and @.iMaxSal != Null and iPeriodPosted != NULL

SELECT * FROM [dbo].[JobsDb_Resumes]

where targetcountryid=@.iCountryID AND

targetstateid=@.iStateID and

jobtypeid=@.iJobTypeID and

minsalary >= @.iminsal and

maxsalary >= @.imaxsal and

resumetext like ('%' + @.sSkill + '%')

ORDER BY [postdate] DESC

Help I am getting an error when I run my insert statement

Please help I am getting the same error no matter how I change my
quotes.
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'Plan'.
conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
[revfinish],[responsible],[action],[title],[dept],[author],[type])
values ('" & request.Form("startdate") &"' ,"&
Request.Form("finishdate") &" ," & Request.Form("revfinish") & ",'" &
Request.Form("responsible") & "','" & Request.Form("action") & "','" &
Request.Form("title") & "','" & Request.Form("dept") & "','" &
session("empid") & "','" & Request.form("type") & "')")
'set Rs =conn.Execute("SELECT * FROM Equipment")
startdate, finshdate,revfinish are all smalldatetime
[Action], responsible, dept, author, type are all text
title is nvarchar
any Ideas?
Try the OLEDB group?
"Tescumeh" <tescumeh@.gmail.com> wrote in message
news:1165868180.115810.136290@.l12g2000cwl.googlegr oups.com...
> Please help I am getting the same error no matter how I change
> my
> quotes.
> Microsoft OLE DB Provider for SQL Server error '80040e14'
> Incorrect syntax near the keyword 'Plan'.
> conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
> [revfinish],[responsible],[action],[title],[dept],[author],[type])
> values ('" & request.Form("startdate") &"' ,"&
> Request.Form("finishdate") &" ," & Request.Form("revfinish") &
> ",'" &
> Request.Form("responsible") & "','" & Request.Form("action") &
> "','" &
> Request.Form("title") & "','" & Request.Form("dept") & "','" &
> session("empid") & "','" & Request.form("type") & "')")
> 'set Rs =conn.Execute("SELECT * FROM Equipment")
> startdate, finshdate,revfinish are all smalldatetime
> [Action], responsible, dept, author, type are all text
> title is nvarchar
> any Ideas?
>
|||What error message are you getting?
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Tescumeh" <tescumeh@.gmail.com> wrote in message
news:1165868180.115810.136290@.l12g2000cwl.googlegr oups.com...
> Please help I am getting the same error no matter how I change my
> quotes.
> Microsoft OLE DB Provider for SQL Server error '80040e14'
> Incorrect syntax near the keyword 'Plan'.
> conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
> [revfinish],[responsible],[action],[title],[dept],[author],[type])
> values ('" & request.Form("startdate") &"' ,"&
> Request.Form("finishdate") &" ," & Request.Form("revfinish") & ",'" &
> Request.Form("responsible") & "','" & Request.Form("action") & "','" &
> Request.Form("title") & "','" & Request.Form("dept") & "','" &
> session("empid") & "','" & Request.form("type") & "')")
> 'set Rs =conn.Execute("SELECT * FROM Equipment")
> startdate, finshdate,revfinish are all smalldatetime
> [Action], responsible, dept, author, type are all text
> title is nvarchar
> any Ideas?
>
|||Imposter!
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Arnie" <99yoda@.newsgroup.nospam> wrote in message
news:u0e%23N%23XHHHA.3616@.TK2MSFTNGP02.phx.gbl...
> Try the OLEDB group?
>
> "Tescumeh" <tescumeh@.gmail.com> wrote in message
> news:1165868180.115810.136290@.l12g2000cwl.googlegr oups.com...
>
|||Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'Plan'.
imposter?
|||> imposter?
We're both "Arnie".
- Arnie
|||Tescumeh said (on or about) 12/11/2006 15:16:
> Please help I am getting the same error no matter how I change my
> quotes.
> Microsoft OLE DB Provider for SQL Server error '80040e14'
> Incorrect syntax near the keyword 'Plan'.
> conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
> [revfinish],[responsible],[action],[title],[dept],[author],[type])
> values ('" & request.Form("startdate") &"' ,"&
> Request.Form("finishdate") &" ," & Request.Form("revfinish") & ",'" &
> Request.Form("responsible") & "','" & Request.Form("action") & "','" &
> Request.Form("title") & "','" & Request.Form("dept") & "','" &
> session("empid") & "','" & Request.form("type") & "')")
> 'set Rs =conn.Execute("SELECT * FROM Equipment")
> startdate, finshdate,revfinish are all smalldatetime
> [Action], responsible, dept, author, type are all text
> title is nvarchar
> any Ideas?
>
When I have a problem like that, I find it very helpful to
break the code into parts so I can assign the SQL statement
to a variable, place a breakpoint in the code and inspect
the variable. Then I try copying the SQL and pasting it
into Query Analyzer. It almost always shows me the exact
problem.
|||Thank you I will try that.

Help I am getting an error when I run my insert statement

Please help I am getting the same error no matter how I change my
quotes.
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'Plan'.
conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
[revfinish],[responsible],[action],[title],[dept],[a
uthor],[type])
values ('" & request.Form("startdate") &"' ,"&
Request.Form("finishdate") &" ," & Request.Form("revfinish") & ",'" &
Request.Form("responsible") & "','" & Request.Form("action") & "','" &
Request.Form("title") & "','" & Request.Form("dept") & "','" &
session("empid") & "','" & Request.form("type") & "')")
'set Rs =conn.Execute("SELECT * FROM Equipment")
startdate, finshdate,revfinish are all smalldatetime
[Action], responsible, dept, author, type are all text
title is nvarchar
any Ideas?Try the OLEDB group?
"Tescumeh" <tescumeh@.gmail.com> wrote in message
news:1165868180.115810.136290@.l12g2000cwl.googlegroups.com...
> Please help I am getting the same error no matter how I change
> my
> quotes.
> Microsoft OLE DB Provider for SQL Server error '80040e14'
> Incorrect syntax near the keyword 'Plan'.
> conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
> [revfinish],[responsible],[action],[title],[dept],[
;author],[type])
> values ('" & request.Form("startdate") &"' ,"&
> Request.Form("finishdate") &" ," & Request.Form("revfinish") &
> ",'" &
> Request.Form("responsible") & "','" & Request.Form("action") &
> "','" &
> Request.Form("title") & "','" & Request.Form("dept") & "','" &
> session("empid") & "','" & Request.form("type") & "')")
> 'set Rs =conn.Execute("SELECT * FROM Equipment")
> startdate, finshdate,revfinish are all smalldatetime
> [Action], responsible, dept, author, type are all text
> title is nvarchar
> any Ideas?
>|||What error message are you getting?
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Tescumeh" <tescumeh@.gmail.com> wrote in message
news:1165868180.115810.136290@.l12g2000cwl.googlegroups.com...
> Please help I am getting the same error no matter how I change my
> quotes.
> Microsoft OLE DB Provider for SQL Server error '80040e14'
> Incorrect syntax near the keyword 'Plan'.
> conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
> [revfinish],[responsible],[action],[title],[dept],[
;author],[type])
> values ('" & request.Form("startdate") &"' ,"&
> Request.Form("finishdate") &" ," & Request.Form("revfinish") & ",'" &
> Request.Form("responsible") & "','" & Request.Form("action") & "','" &
> Request.Form("title") & "','" & Request.Form("dept") & "','" &
> session("empid") & "','" & Request.form("type") & "')")
> 'set Rs =conn.Execute("SELECT * FROM Equipment")
> startdate, finshdate,revfinish are all smalldatetime
> [Action], responsible, dept, author, type are all text
> title is nvarchar
> any Ideas?
>|||Imposter!
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Arnie" <99yoda@.newsgroup.nospam> wrote in message
news:u0e%23N%23XHHHA.3616@.TK2MSFTNGP02.phx.gbl...
> Try the OLEDB group?
>
> "Tescumeh" <tescumeh@.gmail.com> wrote in message
> news:1165868180.115810.136290@.l12g2000cwl.googlegroups.com...
>|||Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'Plan'.
imposter?|||> imposter?
We're both "Arnie".
- Arnie|||Tescumeh said (on or about) 12/11/2006 15:16:
> Please help I am getting the same error no matter how I change my
> quotes.
> Microsoft OLE DB Provider for SQL Server error '80040e14'
> Incorrect syntax near the keyword 'Plan'.
> conn.Execute("INSERT INTO jmiles.Plan([startdate],[finishdate],
> [revfinish],[responsible],[action],[title],[dept],[
;author],[type])
> values ('" & request.Form("startdate") &"' ,"&
> Request.Form("finishdate") &" ," & Request.Form("revfinish") & ",'" &
> Request.Form("responsible") & "','" & Request.Form("action") & "','" &
> Request.Form("title") & "','" & Request.Form("dept") & "','" &
> session("empid") & "','" & Request.form("type") & "')")
> 'set Rs =conn.Execute("SELECT * FROM Equipment")
> startdate, finshdate,revfinish are all smalldatetime
> [Action], responsible, dept, author, type are all text
> title is nvarchar
> any Ideas?
>
When I have a problem like that, I find it very helpful to
break the code into parts so I can assign the SQL statement
to a variable, place a breakpoint in the code and inspect
the variable. Then I try copying the SQL and pasting it
into Query Analyzer. It almost always shows me the exact
problem.|||Thank you I will try that.

Friday, March 23, 2012

Help explain statement start offset and end offset

SELECT TOP 5
total_worker_time/execution_count AS [Avg CPU Time],
(SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN
statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE
statement_end_offset end -statement_start_offset)/2) FROM
sys.dm_exec_sql_text(sql_handle)) AS query_text
FROM sys.dm_exec_query_stats
ORDER BY [Avg CPU Time] DESCI saw this query to give top CPU hogs and I want
to understand this statement within the query above(SELECT
SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset = -1
then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset
end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS
query_text
Where can i learn more about what that statement is actually trying to do ?
Hassan
The view sys.dm_exec_sql_text(sql_handle)) is showing you the currently
executing batch, which may be a block of many commands or could be a stored
procedure. The offsets are showing you which exact statement in the code is
actually running at the moment. This way you are not looking at the whole
batch of commands and trying to figure out which statement is actually
running.
So, picture a stored procedure with 1000 lines. Suppose you run this query
several times and you see the same value being returned, which we might say
are equip to lines 400 to 407, then you may have found the slow point in the
code that could use some extra work in tuning.
RLF
"Hassan" <hassan@.test.com> wrote in message
news:uonSdUVJIHA.5208@.TK2MSFTNGP04.phx.gbl...
> SELECT TOP 5
> total_worker_time/execution_count AS [Avg CPU Time],
> (SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN
> statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE
> statement_end_offset end -statement_start_offset)/2) FROM
> sys.dm_exec_sql_text(sql_handle)) AS query_text
> FROM sys.dm_exec_query_stats
> ORDER BY [Avg CPU Time] DESCI saw this query to give top CPU hogs and I
> want to understand this statement within the query above(SELECT
> SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset
> = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset
> end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS
> query_text
> Where can i learn more about what that statement is actually trying to do
> ?
>

Help explain statement start offset and end offset

SELECT TOP 5
total_worker_time/execution_count AS [Avg CPU Time],
(SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN
statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE
statement_end_offset end -statement_start_offset)/2) FROM
sys.dm_exec_sql_text(sql_handle)) AS query_text
FROM sys.dm_exec_query_stats
ORDER BY [Avg CPU Time] DESCI saw this query to give top CPU hogs and I
want
to understand this statement within the query above(SELECT
SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset = -1
then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset
end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS
query_text
Where can i learn more about what that statement is actually trying to do ?Hassan
The view sys.dm_exec_sql_text(sql_handle)) is showing you the currently
executing batch, which may be a block of many commands or could be a stored
procedure. The offsets are showing you which exact statement in the code is
actually running at the moment. This way you are not looking at the whole
batch of commands and trying to figure out which statement is actually
running.
So, picture a stored procedure with 1000 lines. Suppose you run this query
several times and you see the same value being returned, which we might say
are equip to lines 400 to 407, then you may have found the slow point in the
code that could use some extra work in tuning.
RLF
"Hassan" <hassan@.test.com> wrote in message
news:uonSdUVJIHA.5208@.TK2MSFTNGP04.phx.gbl...
> SELECT TOP 5
> total_worker_time/execution_count AS [Avg CPU Time],
> (SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN
> statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE
> statement_end_offset end -statement_start_offset)/2) FROM
> sys.dm_exec_sql_text(sql_handle)) AS query_text
> FROM sys.dm_exec_query_stats
> ORDER BY [Avg CPU Time] DESCI saw this query to give top CPU hogs and
I
> want to understand this statement within the query above(SELECT
> SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset
> = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset
> end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS
> query_text
> Where can i learn more about what that statement is actually trying to do
> ?
>

Help explain statement start offset and end offset

SELECT TOP 5
total_worker_time/execution_count AS [Avg CPU Time],
(SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN
statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE
statement_end_offset end -statement_start_offset)/2) FROM
sys.dm_exec_sql_text(sql_handle)) AS query_text
FROM sys.dm_exec_query_stats
ORDER BY [Avg CPU Time] DESCI saw this query to give top CPU hogs and I want
to understand this statement within the query above(SELECT
SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset = -1
then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset
end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS
query_text
Where can i learn more about what that statement is actually trying to do ?Hassan
The view sys.dm_exec_sql_text(sql_handle)) is showing you the currently
executing batch, which may be a block of many commands or could be a stored
procedure. The offsets are showing you which exact statement in the code is
actually running at the moment. This way you are not looking at the whole
batch of commands and trying to figure out which statement is actually
running.
So, picture a stored procedure with 1000 lines. Suppose you run this query
several times and you see the same value being returned, which we might say
are equip to lines 400 to 407, then you may have found the slow point in the
code that could use some extra work in tuning.
RLF
"Hassan" <hassan@.test.com> wrote in message
news:uonSdUVJIHA.5208@.TK2MSFTNGP04.phx.gbl...
> SELECT TOP 5
> total_worker_time/execution_count AS [Avg CPU Time],
> (SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN
> statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE
> statement_end_offset end -statement_start_offset)/2) FROM
> sys.dm_exec_sql_text(sql_handle)) AS query_text
> FROM sys.dm_exec_query_stats
> ORDER BY [Avg CPU Time] DESCI saw this query to give top CPU hogs and I
> want to understand this statement within the query above(SELECT
> SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset
> = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset
> end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS
> query_text
> Where can i learn more about what that statement is actually trying to do
> ?
>

Help creating a Transact SQL Insert Statement

Hi there can anyone help me to create a SQL Insert Statement. I dont know SQL at all.

To explain, I have two web pages. search.asp and results.asp.

search.asp has the following.

Form Name: searchForm
Set to: Post
Action: results.asp
Text Field: Keyword
Drop Down: CategoryTable
Drop Down: Location
UserName Session Variable: MM_UserName

results.asp has the following SQL which pulls all the results.

SELECT SupplierName, Location, ShortDescription, TimberSpecies, CategoryTitle, Country, CustomerType
FROM Query1
WHERE TimberSpecies LIKE '%MMColParam%' AND CategoryTitle LIKE '%MMColParam2%' AND Location LIKE '%MMColParam3%' AND CustomerType = 'Trade/Retail'
ORDER BY CategoryTitle, TimberSpecies ASC

The database & form I want to insert into.

tblSearcheResults
idSearch (AutoNumber)
location (Text) "Want to insert the 'Location' result here"
category (Text) "Want to insert the 'CategoryTable' result here"
user (Text) "Want to insert the UserName Session Variable result here"
result (Text) "Want to insert the 'Keyword' result here"

Please ask if u need more info.

Mally

Hi,

INSERT INTO tblSearchResults
(
location,
category,
user,
result
)
VALUES
(
Location, --should be due to the POST action in Request.Form("Location")
category, --should be due to the POST action in Request.Form("category")
user, --should be due to the POST action in Session("MM_UserName")
keyword, --should be due to the POST action in Request.Form("keyword")
)

Variable have to be read first and the query string to be constructed before sending it to SQL Server, keep in mind that you have to quote the string while composing the SQL String.

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

Help creating a SELECT statement for "today"

Hello,

I am attempting to build a MS SQL query that will return data from
"today"; today being current day 8:00AM-10:00PM today. My goal is to
return the data from a table that is written to throughout the day, the
query will provide the current grade of service in our call center.

I am having difficulty defining my where clause:

- I can accomplish my goal my statically defining my 'date between' as
the actual date and time (not ideal)

- I can accomplish the second part of my date using CURRENT_TIMESTAMP;
but I am unable to define the starting point

Here is where I am thus far:

/* We are going to count the total calls into each queue from start of
business today (8:00AM) to now */

select COUNT(Result) as "Total Sales Calls Offered" from
dbo.QueueEncounter
where Direction='0'
and
QueueID='1631'
and
/* This is where I get lost */
Time between DATEPART(day, GETDATE()) and DATEPART(day, GETDATE())

Clearly the last line returns zero as there are no calls between the
same date range. How can I add to that line, or write this to work?

Any thoughts?

Thanks for the help.

-ChrisOn 25 Jan 2006 10:03:53 -0800, Chris wrote:

>Hello,
>I am attempting to build a MS SQL query that will return data from
>"today"; today being current day 8:00AM-10:00PM today. My goal is to
>return the data from a table that is written to throughout the day, the
>query will provide the current grade of service in our call center.
>I am having difficulty defining my where clause:
>- I can accomplish my goal my statically defining my 'date between' as
>the actual date and time (not ideal)
>- I can accomplish the second part of my date using CURRENT_TIMESTAMP;
>but I am unable to define the starting point
>Here is where I am thus far:
>/* We are going to count the total calls into each queue from start of
>business today (8:00AM) to now */
>select COUNT(Result) as "Total Sales Calls Offered" from
>dbo.QueueEncounter
>where Direction='0'
>and
>QueueID='1631'
>and
>/* This is where I get lost */
>Time between DATEPART(day, GETDATE()) and DATEPART(day, GETDATE())
>Clearly the last line returns zero as there are no calls between the
>same date range. How can I add to that line, or write this to work?
>Any thoughts?
>Thanks for the help.
>-Chris

Hi Chris,

You say you want rows for today, 8:00AM-10:00PM. Does this imply that
the table also contains rows outside the 8:00AM-10:00PM time frame that
you don't want to include?

AND Time BETWEEN DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP),
'8:00AM')
AND DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP),
'10:00PM')

Note that this will include a row with time exactly equal to 10 PM, but
exclude a row with time 3 milliseconds after 10PM.

If you want all rows for the whole day (0:00 - 24:00), use
AND Time >= DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP), 0)
AND Time < DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP), 1)

--
Hugo Kornelis, SQL Server MVP|||Awesome Hugo, thanks so much for the help - My query is now nearly
complete; with one last problem....

declare @.today datetime,
@.tomorrow datetime,
@.offered smallint,
@.answeredin120 smallint,
@.GOS smallint

set @.today = convert(char(8), GETDATE ( ), 112)
set @.tomorrow = @.today + 1

-- Find total calls offered
set @.offered = (select COUNT(Result) from dbo.QueueEncounter
where Direction='0' and QueueID='1438' and Time >= @.today and Time <
@.tomorrow)

-- Find total calls answered in 120 seconds
set @.answeredin120 =(select COUNT(Result) from dbo.QueueEncounter
where Direction='0' and QueueID='1438' and Time >= @.today and Time <
@.tomorrow and WaitTime <= 120)

-- Divide the total calls offered by the total calls answered in X
multiplied by 100 to find current GOS ??

set @.GOS = (@.offered)/(@.answeredin120)*100

select @.GOS

The problem is my GOS is being returned as 100 when it is really apprx
77%.
Where did I go wrong?

-Thanks!|||On 25 Jan 2006 14:12:48 -0800, Chris wrote:

(snip)
>-- Divide the total calls offered by the total calls answered in X
>multiplied by 100 to find current GOS ??
>set @.GOS = (@.offered)/(@.answeredin120)*100
>select @.GOS
>The problem is my GOS is being returned as 100 when it is really apprx
>77%.
>Where did I go wrong?

Hi Chris,

Integer division: divide two integers, the result is integer too.

SELECT 1/3
SELECT 1.0/3
SELECT 1/3.0
SELECT 1.0/3.0

The above show that forcing at least one operand to non-integer suffices
to get a result with fraction. In your case, one possible way would be

SET @.GOS = CAST(@.offered AS decimal(10,2)) / @.answeredin120 * 100

Or even

SET @.GOS = 100.0 * @.offerec / @.answeredin120

--
Hugo Kornelis, SQL Server MVP|||Hugo, Again many thanks... I will try this at the office tomorrow.

Cheers.

Wednesday, March 21, 2012

Help Converting Character string to smalldatetime data type

I am attempting to pass a string variable from a form to an SQL statement an
d
I get this error "Syntax error converting character string to smalldatetime
data type"
Your assistance is appreciated in advance....
Here is my code
<%
Dim TESTTHIS__MMColParam1
TESTTHIS__MMColParam1 = "0"
If (Request.Form("StartDate") <> "") Then
TESTTHIS__MMColParam1 = Request.Form("StartDate")
End If
%>
<%
Dim TESTTHIS__MMColParam2
TESTTHIS__MMColParam2 = "0"
If (Request.Form("EndDate") <> "") Then
TESTTHIS__MMColParam2 = Request.Form("EndDate")
End If
%>
<%
Dim TESTTHIS
Dim TESTTHIS_numRows
Set TESTTHIS = Server.CreateObject("ADODB.Recordset")
TESTTHIS.ActiveConnection = MM_CSSMetricsCONN_STRING
TESTTHIS.Source = "SELECT Team, SumofInAdherenceSecsQty /
(SumofInAdherenceSecsQty + SumofOutOfAdherenceSecsQty) AS Adherence FROM
(SELECT TOP 1000 Team, SUM(OutOfAdherenceSecsQty) AS
SumofOutOfAdherenceSecsQty, SUM(InAdherenceSecsQty) AS
SumofInAdherenceSecsQty FROM bo.[National Call Stats] WHERE (Site =
'Dallas') AND ([Date] >='" + Replace(TESTTHIS__MMColParam1, "'", "''") + "')
AND ([Date] <= '" + Replace(TESTTHIS__MMColParam2, "'", "''") + "')
GROUP BY Team, Site ORDER BY Team, Site) DERIVEDTBL"
TESTTHIS.CursorType = 0
TESTTHIS.CursorLocation = 2
TESTTHIS.LockType = 1
TESTTHIS.Open()
TESTTHIS_numRows = 0
%>
Message posted via webservertalk.com
http://www.webservertalk.com/Uwe/Forum...amming/200606/1Run a Profiler trace to see the actual select statement being sent to SQL
Sever. Also, consider using parameters instead of concatenating values.
Parameters are more secure and you don't have to double-up embedded quotes.
Hope this helps.
Dan Guzman
SQL Server MVP
"Chamark via webservertalk.com" <u21870@.uwe> wrote in message
news:6168f7c85cf47@.uwe...
>I am attempting to pass a string variable from a form to an SQL statement
>and
> I get this error "Syntax error converting character string to
> smalldatetime
> data type"
> Your assistance is appreciated in advance....
> Here is my code
> <%
> Dim TESTTHIS__MMColParam1
> TESTTHIS__MMColParam1 = "0"
> If (Request.Form("StartDate") <> "") Then
> TESTTHIS__MMColParam1 = Request.Form("StartDate")
> End If
> %>
> <%
> Dim TESTTHIS__MMColParam2
> TESTTHIS__MMColParam2 = "0"
> If (Request.Form("EndDate") <> "") Then
> TESTTHIS__MMColParam2 = Request.Form("EndDate")
> End If
> %>
> <%
> Dim TESTTHIS
> Dim TESTTHIS_numRows
> Set TESTTHIS = Server.CreateObject("ADODB.Recordset")
> TESTTHIS.ActiveConnection = MM_CSSMetricsCONN_STRING
> TESTTHIS.Source = "SELECT Team, SumofInAdherenceSecsQty /
> (SumofInAdherenceSecsQty + SumofOutOfAdherenceSecsQty) AS Adherence FROM
> (SELECT TOP 1000 Team, SUM(OutOfAdherenceSecsQty) AS
> SumofOutOfAdherenceSecsQty, SUM(InAdherenceSecsQty) AS
> SumofInAdherenceSecsQty FROM bo.[National Call Stats] WHERE (Site =
> 'Dallas') AND ([Date] >='" + Replace(TESTTHIS__MMColParam1, "'", "''") +
> "')
> AND ([Date] <= '" + Replace(TESTTHIS__MMColParam2, "'", "''") + "')
> GROUP BY Team, Site ORDER BY Team, Site)
> DERIVEDTBL"
> TESTTHIS.CursorType = 0
> TESTTHIS.CursorLocation = 2
> TESTTHIS.LockType = 1
> TESTTHIS.Open()
> TESTTHIS_numRows = 0
> %>
> --
> Message posted via webservertalk.com
> http://www.webservertalk.com/Uwe/Forum...amming/200606/1|||Also keep in mind that if something is a valid date it still might not
be able to be converted into smalldatetime (for example dates before
19000101 and after 20790606)
Denis the SQL Menace
http://sqlservercode.blogspot.com/
Chamark via webservertalk.com wrote:
> I am attempting to pass a string variable from a form to an SQL statement
and
> I get this error "Syntax error converting character string to smalldatetim
e
> data type"
> Your assistance is appreciated in advance....
> Here is my code
> <%
> Dim TESTTHIS__MMColParam1
> TESTTHIS__MMColParam1 = "0"
> If (Request.Form("StartDate") <> "") Then
> TESTTHIS__MMColParam1 = Request.Form("StartDate")
> End If
> %>
> <%
> Dim TESTTHIS__MMColParam2
> TESTTHIS__MMColParam2 = "0"
> If (Request.Form("EndDate") <> "") Then
> TESTTHIS__MMColParam2 = Request.Form("EndDate")
> End If
> %>
> <%
> Dim TESTTHIS
> Dim TESTTHIS_numRows
> Set TESTTHIS = Server.CreateObject("ADODB.Recordset")
> TESTTHIS.ActiveConnection = MM_CSSMetricsCONN_STRING
> TESTTHIS.Source = "SELECT Team, SumofInAdherenceSecsQty /
> (SumofInAdherenceSecsQty + SumofOutOfAdherenceSecsQty) AS Adherence FROM
> (SELECT TOP 1000 Team, SUM(OutOfAdherenceSecsQty) AS
> SumofOutOfAdherenceSecsQty, SUM(InAdherenceSecsQty) AS
> SumofInAdherenceSecsQty FROM bo.[National Call Stats] WHERE (Site =
> 'Dallas') AND ([Date] >='" + Replace(TESTTHIS__MMColParam1, "'", "''") + "')
> AND ([Date] <= '" + Replace(TESTTHIS__MMColParam2, "'", "''") + "')
> GROUP BY Team, Site ORDER BY Team, Site) DERIVEDTB
L"
> TESTTHIS.CursorType = 0
> TESTTHIS.CursorLocation = 2
> TESTTHIS.LockType = 1
> TESTTHIS.Open()
> TESTTHIS_numRows = 0
> %>
> --
> Message posted via webservertalk.com
> http://www.webservertalk.com/Uwe/Forum...amming/200606/1|||I am able to see that it is getting to the server because I get a return of
the column headers but I am not getting any data. When I hard code the dates
in the query works fine. I am sending for example 8/1/2005 from the form. If
I take out the two / and send 812005 I get an overflow error?
Dan Guzman wrote:
>Run a Profiler trace to see the actual select statement being sent to SQL
>Sever. Also, consider using parameters instead of concatenating values.
>Parameters are more secure and you don't have to double-up embedded quotes.
>
>[quoted text clipped - 43 lines]
Message posted via webservertalk.com
http://www.webservertalk.com/Uwe/Forum...amming/200606/1|||On Wed, 07 Jun 2006 20:12:46 GMT, "Chamark via webservertalk.com"
<u21870@.uwe> wrote:

>I am able to see that it is getting to the server because I get a return of
>the column headers but I am not getting any data. When I hard code the date
s
>in the query works fine. I am sending for example 8/1/2005 from the form. I
f
>I take out the two / and send 812005 I get an overflow error?
You will get an error, as '812005' does not convert to datetime:
select convert(datetime,'812005')
Server: Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in
an out-of-range datetime value.
The most reliable format for a date string is YYYYMMDD:
select convert(datetime,'20050801')
--
2005-08-01 00:00:00.000
Roy Harvey
Beacon Falls, CTsql

help appreciated with this select statement please

How can I do this in one query
I've got a table like this
ID RESOURCEID DATE QUANTITY
The Id is unique (but just a counter not of interest here), there may be one
resourceid for each date and an asscoiated quantity.
I want to select all resourceid (distinct) and I just want just the
resourceid and the date and quantity associated
with that post that is less than today but nearast in time.
To examplifY
if some records look like like this
ID RESOURCEID DATE QUANTITY
1 1 2003-12-01 1.3
2 1 2004-01-25 1.4
3 2 2002-01-01 1.7
4 2 2003-07-27 2.8
I want my select statement to return only the two following post
2 1 2004-01-25 1.4
4 2 2003-07-27 2.8
That is one post for each resource and the post should be the one were the
date is less than today but closest in time
I want to do this without using stored procedure or view, since I'm not
allowed to create objects in the database.SELECT id, resourceid, date, quantity
FROM SomeTable AS S
WHERE date = (SELECT MAX(date)
FROM SomeTable
WHERE date < CONVERT(CHAR(8),CURRENT_TIMESTAMP,112)
AND resourceid = S.resourceid)
--
David Portas
SQL Server MVP
--

help appreciated with this select statement please

How can I do this in one query
I've got a table like this
ID RESOURCEID DATE QUANTITY
The Id is unique (but just a counter not of interest here), there may be one
resourceid for each date and an asscoiated quantity.
I want to select all resourceid (distinct) and I just want just the
resourceid and the date and quantity associated
with that post that is less than today but nearast in time.
To examplifY
if some records look like like this
ID RESOURCEID DATE QUANTITY
1 1 2003-12-01 1.3
2 1 2004-01-25 1.4
3 2 2002-01-01 1.7
4 2 2003-07-27 2.8
I want my select statement to return only the two following post
2 1 2004-01-25 1.4
4 2 2003-07-27 2.8
That is one post for each resource and the post should be the one were the
date is less than today but closest in time
I want to do this without using stored procedure or view, since I'm not
allowed to create objects in the database.SELECT id, resourceid, date, quantity
FROM SomeTable AS S
WHERE date =
(SELECT MAX(date)
FROM SomeTable
WHERE date < CONVERT(CHAR(8),CURRENT_TIMESTAMP,112)
AND resourceid = S.resourceid)
David Portas
SQL Server MVP
--

Help Altering Database Table from NULL to NOT NULL

I would drop and add the table but the data can't be deleted. So if anyone could help with the statement it would be greatly appreciated. ThanksYou alter columns to NOT NULL, not tables. Can you explain why you're trying to do this? What are you going to put in all the columns that have NULL? Why does the table have NULL in the first place. You should post what the table looks like with a couple sample rows.|||My apologies I meant a column. Currently a remote table that I'm adding a new column to where the people there have no idea how to use SQL Server. I've made a new SQL script to add a new column and have to set the column to NULL since its a new column being added to an existing table. After the apropriate data is in the new column I need to set the column to NOT NULL for future entries.....|||Could you add the column allowed to have NULL, then update the table where the column get's some value, then alter the table setting the column to NOT NULL?|||Thats pretty much what I'm trying to do but via scripts. Circumstances keep me from doing this manually so I'm trying to get it setup via a script.....|||so at which of the three steps are you stuck?|||Are you just trying to change the column null to not null if something is meet?|||if exists (select 1 from your_table where new_column is null)
raiserror ('You can't make column NON-NULLABLE if there is at least 1 NULL in it!, 15, 1)
else
alter table your_table alter column new_column <data_type> not null

Monday, March 19, 2012

help : Update statement

Here's the statement I need some help with:

SELECT UID FROM sandbox.jobs WHERE username = 'username' order by UID desc
FROM sandbox.timespent;
UPDATE sandbox.timespent
SET UID = UID, Username = 'username', Job_Description = 'test_job'
WHERE Username = 'username'
;

what' i'm trying to do is insert the job description to the most recent entry (which is why i sorted) but it's adding the job description everywhere it sees username (which is more than once) so i need it to update the latest line

something like:

UID | Username | Job description
1 username test_job
2 username test_job1
3 username test_job2

when it updates it should add to UID 3 since it's the most recent. if anyone knows how to write the update statement please let me know. THANK YOU!

What determines if a row is 'most recent'?

Is it the larger UID?

What are the other columns in the tables?

|||I'm not sure how to make it so it selects the most recent. I wanted to sort it and select the first one (which would be most recent) but I'm not sure how to select the first one.

SELECT UID FROM sandbox.jobs WHERE username = 'username' order by UID desc LIMIT 1
FROM sandbox.timespent;
UPDATE sandbox.timespent
SET UID = UID, Username = 'username', Job_Description = 'test_job100'
WHERE UID = UID
;

that's what i wanted it to do, but instead of
WHERE UID = UID i want it to be something like WHERE UID = "most recent UID" some how

|||

So how do you determine which is the 'most recent UID'?

Is is the largest UID value? (It's still not clear.)

|||alright i'll try to explain myself better... I'm writing a program in vb.net

the table looks something like this:

UID | Username | Job | PLC_option | PLC_software
0 user1 9 option1 software1

that's what I want the data to look like. When the program runs, it adds a new UID and the users username to the table... another form opens and the user selects a job, i want the job to be added to that same column (where '9' is) but what's happening is the username dissapears. Another form will come up and the user selects the PLC option

what i'm trying to accomplish is the ID and username gets inserted and then the job and plc options get updated into that same row...

hope that's a little more clear.. thank you
|||

Kenny,

There are at least a couple of ways to go on this. First, let me ask a couple more questions.

What is the code that inserts the new UID and UserName into the table?

How is that code executed?

|||that's where i'm not sure... right now i have this code...

this is in my main form where the UID and username gets sent to the table...

strsuccess = " INSERT INTO sanbox.timespent "
strsuccess &= " ( `username ` ) VALUES ( "
strsuccess &= " '" & GlobalV.strUsername & "');"
x.dbCommand = strsuccess
x.ExecuteNonQuery()

strTime = "Update(sandbox.timespent) "
strTime &= " SET UID = UID , Username = '" & GlobalV.strUsername & "';"
strTime &= " WHERE(uid = uid) "
x.dbCommand = strTime
x.ExecuteNonQuery()

not sure if i did that part right but what I want to do is add a new UID to the form and add the username right next to that UID as a new session kind of deal... once the user proceeds to the next form this code is executed:

strjob = "Update(sandbox.timespent) "
strjob &= " SET job_description = '" & lstJobList.SelectedItem & "'"
strjob &= " WHERE username = '" & GlobalV.strUsername & "';"
x.dbCommand = strjob
x.ExecuteNonQuery()
x = Nothing

i'm pretty sure i'm not doing that part right, i want the job item to be added right next to the username... but what's happening is, the job item is filling in everywhere it finds the username to be the variable value...

i'd like to have it added to the newest UID, which would only add once... that's why i mentioned possibly making it so " WHERE UID = " some kind of uid variable "

it's a little hard to explain but if you can figure out how to add the job item once to the newest column i'd really appreciate it. thanks!

|||

OK, I see a couple of problems.

A couple more questions.

Where is the UID created?

Is it a IDENTITY field value from the table?

And What version/Edition of SQL Server? ( 2000 / 2005 ) ( Express / Standard / Enterprise )

|||the UID is unique and is incrimented by 1, it's the primary key if that helps.|||

Kenny,

You didn't respond about the version/edition of SQL Server, so I will assume that you are using SQL 2005.

This will not execute in your application, but it should point you in the direction that you need to go to make it work as you desire.

First, you need to capture the UID into a newly created application variable (scope it appropriately).

To do so, change the query type to ExecuteQuery so you can get a resultset.

Change the query to your version of this:


INSERT INTO SandBox.TimeSpent ( UserName )
OUTPUT inserted.UID
VALUES ( GlobalV.strUserName )

The application will do something like:

GlobalV.UID = x.ExecuteQuery

At the execution of the insert query, you will have the UID for the newly inserted row -which contains the UserName.

Then your UPDATE statement should be somewhat like this:


UPDATE SandBox.Timespent
SET Job_Description = {Your listbox.SelectedItem for JobDescription}
WHERE UID = GlobalV.UID

By using the UID, you will UPDATE ONLY the row you desire. AS you noticed, when you UPDATE by UserName, you are updating all rows with that UserName.

Monday, March 12, 2012

Help !!!!!using case statements in update

Hi,
I have this update statement that works, it updates the totalamount to calc amount, but I want to update totalamount only when it is not equal to calcamt.I have tried many things but in vain.Can some one please help me.
How do i use case statements to update only when totalamount!=calcamt.

update c
set totalamount= calcamt
from Prepay c
JOIN
( select sum(amt) as calcamt, payid
from pay
group by payid
)b ON b.payid= c.payid
where c.cust_no='somenum'

Try this:

Code Snippet

update c
set totalamount= calcamt
from Prepay c
JOIN
( select sum(amt) as calcamt, payid
from pay
group by payid
)b ON b.payid= c.payid and b.calcamt <> c.dailytotalamount

where c.cust_no='somenum'

Help !!! Database failed to restore

I had to restore SQl Server v7 but the database has failed to reinstall..

sql statement

restore database sebr from disk = "c:\Projects\EBR\Database" with norecovery, stats=1, replace

Response after about 5 mins

Server: Msg 3624, Level 20, State 1, Line 1
Location: upgraddb.cpp:214
Expression: tableIndex < ARRAY_LEN (upgradeMap)
SPID: 7
Process ID: 800

Connection Broken

Can anybody give any advice ?

Hi!

What SQL version you use to create backup and what version of server where you restore it?

|||Thanks for your reply S.G. - it was the same version (v7.0)|||any SP? If it wont help try to not replace but restore it with the different name and if it help replace these dbs.

Help ! How do i refer to the deleted table into a trigger statement ?

Hi there,

Could somebody post some simple example how one can refer to
a column in the 'deleted' temporary table within a trigger definition ?
Should the 'deleted' and 'inserted' temp tables be declared, or they are
'implied' ?

I keep having this msg when trying to create a trigger
"The column prefix 'deleted' does not match with a table name or alias name
used in the query"

Thanks for your inputs,
Eddy.[posted and mailed, please reply in news]

Eddy Fontaine (eddy.fontaine@.advalvas.be) writes:
> Could somebody post some simple example how one can refer to
> a column in the 'deleted' temporary table within a trigger definition ?
> Should the 'deleted' and 'inserted' temp tables be declared, or they are
> 'implied' ?

They are implied. You just use them.

> I keep having this msg when trying to create a trigger
> "The column prefix 'deleted' does not match with a table name or alias
> name used in the query"

May I guess that you are using dynamic SQL? Code executed in EXEC() or
sp_executesql is not part of the trigger, but constitutes a scope on
its own.

A practical workaround is to say:

SELECT * INTO #deleted FROM deleted
SELECT * INTO #inserted FROM inserted

first in the trigger.

This can even be useful in a trigger that does not use dynamic SQL,
particular if multi-row operations are common, because you can get
better performance. The virtual tables inserted and deleted are
not very efficient when they get some size.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Eddy Fontaine (eddy.fontaine@.advalvas.be) writes:
> Thanks Erland,
> I was trying to refer to a column in the deleted temp table with
> 'deleted.column_name'...
> My sql server does not like this !

Since you never posted the code to the trigger that gave you the
error message, I cannot say what your problem really was. Judging from
the code you post now, may you tried with:

> UPDATE DemographicData SET Lastupdate = getdate()
> WHERE ID = deleted.ID

which is not legal, but that has nothing to do with inserted/deleted,
but with the fact that you must name a table in a query in a FROM
clause or after INSERT/DELETE/UPDATE.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

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

Friday, March 9, 2012

Help - SQL Keyword Error (SQLCODE -199)

I continue to receive an error (SQLCODE -199) on a statement that works in other sql programs. I have looked and looked at it, it looks fine to me. Can someone please look at the following code and tell me if you see any reason for the error? Object XSROLOTV1 in library GPSMODS not found. The error I receive is below.
Any help is appreciated. Thank you.

ERROR -
Object XSROLOTV1 in GPSMODS type *FILE not found.
Object XSROLOTV1 in QTEMP type *QMQRY deleted.
IMPORT source record length exceeds 79 characters.
Warnings issued on IMPORT QUERY command.
IMPORT operation completed successfully.
Warning returned by query management.
Keyword FROM not expected. Valid tokens: ) ,.
RUN QUERY command failed with SQLCODE -199.
RUN QUERY command ended due to error.
STRQMQRY command failed.
Function check. QWM2701 unmonitored by RUNGPSSQL at statement 13200,

SQL -

(INT(YEAR(DATE((DAYS(DATE(SUBSTR(CHAR(INT(LTDDAT/10000)) FROM 1 TO 4) || '-' || SUBSTR(CHAR(DEC((INT(LTDDAT/100) - INT(LTDDAT/10000)*100))/100) FROM 2 FOR 2) || '-' || SUBSTR(CHAR(DEC(LTDDAT - INT(LTDDAT/100)*100)/100) FROM 2 FOR 2) ))) - (DAYOFWEEK(DATE(SUBSTR(CHAR(INT(LTDDAT/10000)) FROM 1 FOR 4) || '-' || SUBSTR(CHAR(DEC((INT(LTDDAT/100) - INT(LTDDAT/10000)*100))/100)) FROM 2 FOR 2) || '-' || SUBSTR(CHAR(DEC(LTDDAT - INT(LTDDAT/100)*100)/100) FROM 2 FOR 2)))) + 1))) *100)

+

INT(WEEK(DATE((DAYS(DATE(SUBSTR(CHAR(INT(LTDDAT/10000)) FROM 1 FOR 4) || '-' || SUBSTR(CHAR(DEC((INT(LTDDAT/100) -INT(LTDDAT/10000)*100))/100) FROM 2 FOR 2 || '-' || SUBSTR(CHAR(DEC(LTDDAT - UBT(LTDDAT/100)*100)/100) FROM 2 FOR 2)))) (DAYOFWEEK(DATE(SUBSTR(CHAR(INT(LTDDAT/10000)) FROM 1 FOR 4) || '-' || SUBSTR(CHAR(DEC((INT(LTDDAT/100) - INT(LTDDAT/10000)*100))/100) FROM 2 FOR 2 || '-' || SUBSTR(CHAR(DEC(LTDDAT -INT(LTDDAT/100)*100)/100) FROM 2 FOR 2)))) + 1))) AS LTDDATYWYou can't pass the keyword FROM as a column alias within a SUBSTR function.

... SUBSTR(CHAR(DEC(LTDDAT-INT(LTDDAT/100)*100)/100) FROM 2 FOR 2)

Isn't the syntax supposed to be SUBSTR(string, start, length). The parenthesis after 2 FOR 2 ends the SUBSTR function.

Find the integer value, multiply by 100, subtract fro LTDDAT, convert to decimal, divide by 100, convert to character, then find a Substring within that resulting character string.

Maybe you only need to replace FROM with a comma, and replace FOR with a comma. the rest looks good.