EXEC String With Datediff

Mar 7, 2001

I am using the EXEC function in order to specify which view to access. However I can not get the datediff to work with it....does anyone have any clues?

View 1 Replies


ADVERTISEMENT

Exec @string

Oct 24, 2005

I am trying to do an insert statement utilizing a variable string.

something like:

Set @cString = 'SELECT top 10 *
FROM OPENDATASOURCE(
' + char(39) + 'SQLOLEDB' + char(39) + ',' + char(39) +
'Data Source=' + @lServer + ';User ID=' + @user + ';Password=' + @pword + char(39) + '
).myServer..

Insert into #Temp_table (field1, field2)
select exec @cString

--What is the syntax for this?

View 3 Replies View Related

EXEC String Problem

Aug 21, 1998

Hi All,

I am using SQL Server 7 Beta 3 and I am having trouble with using a variable
in an EXEC statement.

I have a stored procedure that is designed to retrieve a serial
number from a table and then increment it by one(1) and return the
original serial number to the calling function.

As long as the table name is hardcoded the following code works fine:


CREATE PROCEDURE IncrementSerialIDNo
(@serial_num_temp varchar(15), @serial_num_output varchar(15) output)

AS
BEGIN TRANSACTION
BEGIN


SELECT @serial_num_temp = tblSerialNo.SerialNo
FROM tblSerialNo

SELECT @serial_num_output = @serial_num_temp

UPDATE tblSerialNo
SET tblSerialNo.SerialNo =
CONVERT(varchar(15),(CONVERT(integer,@serial_num_t emp ) + 1))

IF (@@error = 0)

COMMIT TRANSACTION

ELSE

ROLLBACK TRANSACTION

END

RETURN


However, if I change the table name to a variable that is passed to the
stored procedure as a argument, I need to use the EXEC statement.

My problem is that for the EXEC statement to work I need to escape the
variables and I run into a problem with the " = " ( equal sign ).

Example:


DECLARE @SerialTable as varchar(30), @CompanyNo as varchar (3)

SELECT @CompanyNo = `001`

SELECT @SerialTable = `tblSerialNo` + @CompanyNo

EXEC ( `SELECT ` +@serial_num_temp + `= SerialNo FROM ` +
@SerialTable )


Following is the error message that I keep getting:

Server: Msg 170, Level 15, State 1
[Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax
near `=`.



No amount of testing with different qoutes or doublequotes and such,
have made any difference.

I have tried numerous variations on the above SELECT statement with the
same end result of the error on the "=" sign.

I cannot seem to assign one variable to another using the "=" (equal sign)
in an EXEC statement.

Does anyone have example code of using the equal sign to assign one variable
to another in an EXEC statement or can someone point me in the right direction?

Thanks in advance for any and all help.



jeff alerta
jeff@nestworks.com

View 5 Replies View Related

Linked Servers And String Exec

Dec 17, 2003

Hi.

I have been trying to find a solution to this for some time now. Was wondering if some1 had done is earlier and has a solution.

I have a 2 server machines.
Namely: ServerOne and ServerTwo

ServerOne (main server, On 1 machine.)
Table - Foofoo

ServerTwo (secondary server, on another machine)
Table - Booboo

I want to be able to link these two servers and work with them.

At the moment I do something like this.
NB. My Stored Procedure is on ServerOne

declare @server varchar(100)

Select @server=Servername from ServerOne.systemsettings where name='secondary'
-- @server is not equal to 'ServerTwo'
declare @str varchar(8000)
set @str = '
select *
from Foofoo f
join ' + @server + '.myDB.dbo.Booboo b on b.id = f.id '

exec(@str)

My problem is that this works fine but I do not like working with long strings and then executing them at the end.

I have also been told that SQL's performance on this is not entirely that well as normal select's would be.'

Another thing that could be used is SQl's own linked servers method but apparently out system was designed some time ago and a lot of things have been developed around the current technic.

Our server names also change quite frequently making hadcoding server names difficult.

Using the string exec convention also hides from sql when you do a dependency search of a particular table.

Is there a way I can save the server name on @server and then just add it to the select stmt without using the long stringing idea.

Any feedback with ideas and solutions will be greatly appreciated.

Bhit.

View 1 Replies View Related

Confused Exec With A Compound Sql String

Aug 1, 2000

I am trying to make up a SQL string which will be executed with the Exec command

I want to add a return column that is not in the table, and the table columns:

something like
Select @Ten As Ten, @Tablename.* From @Tablename (
where @Ten has an integer value. )
The statement was originally:
select @SQL = 'select * from ' + @TempName
exec (@SQL)
which had no problem. Then I needed to add an extra column of static data to all the returned rows, and confusion !!!!!

Thanks,
Judith

View 1 Replies View Related

Complex Concatenated String For An 'exec(@sql) '

Aug 10, 2000

I have:

<<Select @SQL = 'Select Keyword, SICCode From zlk_SICCodeKeyword Where Keyword like ''%' + @KeywordOrSIC + '%''' + ' order by Keyword'

exec(@SQL)>>
which works fine, but I want to modify it to do this

<<Select Replace(Keyword,',',' ') AS Keyword, SICCode From zlk_SICCodeKeyword Where Keyword like 'real%' order by Keyword >>

which works from the query window but I can not get the right combination around the 'replace section' to make up a string for the exec.

All help greatly appreciated
Judith

View 1 Replies View Related

Set Local Variables When EXEC-ing A Sql String

Nov 23, 2006

Hey guys, needless to say I'm new at this.

What I'm trying to accomplish is to execute a SQL string via exec and inside it set the value of a local variable. I understand that I cannot do this the way I'm currently doing it because an Executed string runs in a scope of its own so local variables are invisible. And sure enough this is the error I get. So how do I make this work?

Code snip:




declare @ErrMessage as varchar(1000)
set @Sql = 'if exists ( select * from ' + @TargetTable + ' where (' + @ValueField + '=' + '''' + @NewValue + ''''
set @Sql = @Sql + ' and ' + @TagField + '= ' + '''' + @Tag + '''' + '))' + @CRLF
set @Sql = @Sql + 'set @ErrMessage = ''Insertion could not be performed. ' + @NewValue + ' is already an entry in the table. '''


So what I want is check if a certain table has entries...what table? I don't know, there are tens that this check will apply to. And if that tavle has an entry that satisfies the where clause then assign the appropriate error message to @ErrMessage.

I understand sp_executesql might do the trick because it allows passing local params back and forth.

Any ideas on how to make this work? I appreciate the effort.

View 3 Replies View Related

Error While Executing A A Query String Using EXEC Statement

Sep 18, 2007

Hi,
I have written a stored proc to bulk insert the data from a data file.
I have a requirement that i need to insert the data into a table of which the name is not known. I mean to say that the table name will be passed as a parameter to the stored proc. And also i need to insert the date that will also be passed as the parameter to the stored proc

The follwing statement works fine if i give the table name directly in the query



Code Snippet

DECLARE @LastUpdate varchar(20)

SET @LastUpdate = 'Dec 11 2007 1:20AM'

INSERT INTO Category
SELECT MSISDN, @LastUpdate FROM OPENROWSET( BULK '\remotemachinedatafile.txt',
FORMATFILE = '\remotemachineFormatFile.fmt',
FIRSTROW = 2) AS a



To satisfy my requirement ( i.e passing the table name dynamically , and the date) , i have formed the query string ( exact one as above ) and passing it to EXEC statement. But its failing as explained below






Code Snippet

@Category - Will be passed as a parameter to the stored proc


DECLARE @vsBulkSQL VARCHAR(MAX)

DECLARE @LastUpdate varchar(20)

SET @LastUpdate = 'Dec 11 2007 1:20AM'

SELECT @vsBulkSQL ='INSERT INTO '+ @Category + ' SELECT MSISDN, ''' + @LastUpdate +''' FROM OPENROWSET ' + '( BULK ' + '''' + '\remotemachinedatafile.txt'+ ''''+ ' ,' +
+ ' FORMATFILE ' + '=' + ''''+ '\remotemachineFormatFile.fmt'+ ''''+ ',' +
' FIRSTROW ' + '=' + '2' + ')' + ' AS a'

Print @vsBulkSQL - This prints the folliwing statement


INSERT INTO Category SELECT MSISDN, 'Dec 11 2007 1:20AM' FROM OPENROWSET ( BULK '\remotemachineDataFile.txt' , FORMATFILE ='\remotemachineFormatFile.fmt', FIRSTROW =2) AS a


Exec @vsBulkSQL - This statement gives the following error

The name 'INSERT INTO Sports SELECT MSISDN, 'Dec 11 2007 1:20AM' FROM OPENROWSET ( BULK '\remotemachineSecond.txt' , FORMATFILE ='\remotemachineFormatFile.fmt', FIRSTROW =2) AS a' is not a valid identifier.






Can any one please point out where am i doing wrong? Or do i need to do anything else to achive the same

~Mohan

View 4 Replies View Related

Transact SQL :: Using EXEC To Execute A Formula Stored In A String

May 31, 2005

Basically, I have a table with a column that stores mathematical formulas in string format.  When my UDF is executed, it needs to select an appropriate formula from this table and evaluate it using values that are stored in local variables. 

Look at the example below:

Suppose I have a string named @vcFormula that contains the following:"@dVar1 + @dVar2 / @dVar2"Now suppose I have a variable named @dVar1 that contains a value of 1.0, and variable @dVar2 contains a value of 2.5.  I can use the REPLACE function to change my original string to look like this:"1.0 + 2.5 / 2.5"

Now I want to execute this string and find the numeric result, placing it in a variable named @dResult.  The following works, but presents a problem:CREATE TABLE #Result (dResult decimal(20, 10))INSERT #Result EXEC('SELECT ' + @vcFormula)SELECT @dResult = dResult FROM #ResultThe problem with using this method comes from the fact that I need to be able to evaluate @vcFormula from within a user-defined function, but temporary tables are not allowed inside UDF's. 

So I attempted to change the temporary table above into an instance of the TABLE data type.  This didn't work either because EXEC cannot be used to populate instances of the TABLE data type.  Then I came up with the bright idea to put the code above in a SP and call the SP from the UDF, but of course UDF's are not allowed to call SP's. Specifically, is there any way to execute a command/formula that is contained within a string other than by using EXEC? 

View 10 Replies View Related

How Do I Use A @variable To Hold On Value Return From An Exec (&#39;string Command&#39;) Statement.

Sep 19, 2000

How do I use a @variable to hold on value return from an exec ('string command') statement.

Example for:

declare @OldID int
declare @cmd varchar(255)
declare @db varchar(25)
declare @OldOwner varchar(25)

set @db = 'DBNAME'
set @OldOwner = 'USERNAME'

select @cmd = 'select uid from ' + ltrim(rtrim(@db))'..sysusers where name = ' + "'" + ltrim(rtrim(@OldOwner)) + "'"
exec (@cmd)

How can I use @OldID to hold on UID return from this statement.

When I try use:
select @cmd = 'select @OldID = uid from ' + ltrim(rtrim(@db))'..sysusers where name = ' + "'" + ltrim(rtrim(@OldOwner)) + "'"
then I'm getting a error message: @OldID not declare.

Thanks.

View 2 Replies View Related

Can Exec Select But Can't Exec Sp

Oct 31, 2007

I have two SQL Server 2000 (one is localhost, one is remote with VPN IP 192.168.5.4).

I can select * from [192.168.5.4].db.dbo.test but I can't exec [192.168.5.4].db..spAdd in localhost.

These select and sp is OK for 1 or 2 week without any problem,but it didn't work one day.

Can some one explain why?

View 5 Replies View Related

Datediff

Dec 5, 2005

If I wanted to get everyone DOB who is over 18 how would I do that? I am currently trying something like this, but no luck...


Declare @todays_date datetime

Select from person
CASE
WHEN dateadd(year, datediff (year, Date_Of_Birth, @Todays_Date), Date_Of_Birth) > @Todays_Date -- Date of Birth check
THEN datediff (year, Date_Of_Birth, @Todays_Date) - 1
ELSE datediff (year, Date_Of_Birth, @Todays_Date)
END
>= 18

View 3 Replies View Related

DateDiff

Jul 27, 2004

I'm using a datediff(mi, start, stop) to get the duration of an operation. i want it displayed in HH:MM format. can anyone help me w/ a way to do that????



tia,
e3witt

View 4 Replies View Related

Datediff Or MAX?

Mar 9, 2004

Hello,

My string is:

SELECT weight FROM progress WHERE dateInput = (SELECT MAX(dateInput) FROM progress) AND memberID = 1

The problem is that the MAX dateInput doesn't belongs to memberID 1. It belongs to memberID 2. What I want is that I wanna choose the MAX Date of memberID 1. I thought of maybe using datadiff function. But I don't know how to make the datediff statement. Maybe I can write the datediff statement whereby the least datediff between the dateInput and getdate() will be the row I want. I really appreciate the person that helps me this problem... Thanks 1st of all!

View 2 Replies View Related

DateDiff

Apr 15, 2004

I am trying to select records from whatever the current date would be and 12 months before whatever the current date is. How would I go about doing this. The table that I am trying to do this with has a year column and a month column.

I was playing with the date diff function, but I can only get dates from the specified date range. I need it to be where if I run it tomorrow, it will get that day and everything within the last 12 months.

View 7 Replies View Related

DATEDIFF?

Apr 25, 2008

I need to get a listing of all persons who are atleast 18 years of age. A date of birth field in the database is in this format:

4/25/2008 12:00:00 AM

My solution would be where the difference between the current date and the dob is >= 18.

I tried...

select * from table where datediff(yy,dob,getdate)) >= 18.

But this only seems to subtract the years and ignore the days/months, which I need. Could anyone provide the syntax I need?

Help is appreciated. Thanks.

View 3 Replies View Related

Datediff

Jun 24, 2008

Hi there i am using the datediff funtion but it does not seem to be inclusive of the two dates eg
SELECT DATEDIFF(day, s_Date, e_date) AS NumberOfDays,*
FROM weekendtest

i know i could do
SELECT DATEDIFF(day, s_Date, e_date)+1 AS NumberOfDays,*
FROM weekendtest

but i was just wondering if there some other function i should use that would be more appropriate

View 3 Replies View Related

Datediff

Oct 21, 2004

Hi
I've a problem!!!
i want to use datediff thats no problem. But the first parameter has to
be parameterised. What datatype do i declare it as. i declare it as varchar
it returns me an error : Invalid parameter 1 specified for datediff.

i'm doing this in a stored procedure.

Is there a way out or do i've to use the good old 'IF' or 'Case' ?



regards
pradeep

View 1 Replies View Related

DateDiff In Sql?

Oct 19, 2006

Hi,
I have a Table Where I have Two Date columns and I want to find the Differnce in the 3rd column.ie DateReceived - AsOnDate = NoofDays.I tried this code
SELECT SRNO,CONVERT (VARCHAR,AsonDate,102)as ASONDATE,CONVERT(VARCHAR, DateReceived, 102) AS DateReceived,CONVERT(VARCHAR, DateAcknowledged, 102) AS NoofDays,
sum(CASE WHEN DATEDIFF(DAY, DATERECEIVED,ASONDATE, GETDATE())
FROM Details


Plz help me...

Thanks

View 7 Replies View Related

DATEDIFF

Jan 27, 2008

SELECT DATEDIFF(mm,0,'01/25/2008')
Returns 1296 what does it represent...

Thanks

View 2 Replies View Related

DATEDIFF

Feb 29, 2008

Could somebody please explain to me why I get the following results:


select datepart (ww, '10/02/08') --returns 6

select datepart (ww, '18/02/08') --returns 8

select datediff (ww, '10/02/08', '18/02/08') -- returns 1

I was expecting the third query to return 2.

Thanks.

View 11 Replies View Related

HELP Me In This Datediff() Function....

Nov 23, 2006

Hi, I am facing problem rite now.. I want to calculate the date different minutes between 23:00:00 and 01:00:00.
My code :
datediff(Minute,'01:00:00','23:00:00')
The result is 1320 minutes. (22 hours)... But, the result that I want is 120 minutes (2 hours)....
Can anybody help ???
Thanks in advance...

View 2 Replies View Related

Datediff Problem

Jan 12, 2007

I'm trying to use the same select statement I used in classic SQL, but it isn't working.  I get a "The server tag is not well formed." error.
I'm trying to return all the records where the date in a particular field are over 60 days old.  My select statement is:
"SELECT [ReNewAd], [Male or Female], [File2], [PHOTO], [First Name], [Last Name], [City], [State], [NewAd] FROM Members Where ('NewAd' IS NOT NULL AND (DateDiff('d', [NewAd], '" & Now() & "') <= 60)) order by [NewAd] Desc"
I've been looking through the datediff posts, but I'm not making any sense of what I'm reading.  Can anyone see what I'm doing wrong?
Thanks, Diane

View 5 Replies View Related

Using CASE And DATEDIFF

Jun 14, 2007

I'm trying to create a stored procedure that will return a set of data. An input parameter (if specified) will determine what topics will be show based on the date the item "datetime". ALTER PROCEDURE [dbo].[discussions_GetTopics]@board_id as int,@PageNumber INT,@TopicsDays  INT = NULL,@TopicsPerPage INT,@HowManyProducts INT OUTPUTAS-- Declare the table that will store all the topics for the given board_idDECLARE @Topics TABLE(RowNumber INT,topic_id INT,topic_title VARCHAR(50),topic_replies INT,topic_views INT,topic_type INT,post_id int,post_time DATETIME,Topic_Author_UserName nvarchar(256),Topic_Author_ID uniqueidentifier,Post_Author_Username nvarchar(256),Post_Author_ID uniqueidentifier)-- populate the tableINSERT INTO @TopicsSELECT     ROW_NUMBER() OVER (ORDER BY discussions_topics.topic_id), discussions_Topics.topic_id, discussions_Topics.topic_title, discussions_Topics.topic_replies, discussions_Topics.topic_views, discussions_Topics.topic_type, discussions_Posts.post_id, discussions_Posts.post_time, user_1.UserName AS Topic_Author_Username,                      user_1.UserId AS Topic_Author_ID, user_2.UserName AS Post_Author_Username, user_2.UserId AS Post_Author_IDFROM         discussions_Topics INNER JOIN                      discussions_Posts ON discussions_Posts.post_id = discussions_Topics.topic_last_post_id INNER JOIN                      aspnet_Users AS user_1 ON user_1.UserId = discussions_Topics.topic_poster INNER JOIN                      aspnet_Users AS user_2 ON user_2.UserId = discussions_Posts.poster_idWHERE     (discussions_Topics.board_id = @board_id ANDCASE @TopicsDays    WHEN '1' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 1    WHEN '2' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 7    WHEN '3' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 14    WHEN '4' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 30    WHEN '5' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 90    WHEN '6' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 180    WHEN '7' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 365END)-- return the total number of products using an OUTPUT variableSELECT @HowManyProducts = COUNT(topic_id) FROM @Topics-- Return the specified page of topicsSELECT * from @TopicsWHERE RowNumber > (@PageNumber - 1) * @TopicsPerPageAND RowNumber <= @PageNumber * @TopicsPerPage  I need help where the  "CASE @TopicsDays
    WHEN '1' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 1
    WHEN '2' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 7
    WHEN '3' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 14
    WHEN '4' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 30
    WHEN '5' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 90
    WHEN '6' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 180
    WHEN '7' THEN DATEDIFF(day, discussions_Topics.topic_time, getdate()) <= 365
END" Is...   Im not doing it right. Can someone help me?

View 1 Replies View Related

DateDiff / DateAdd - Please Help Me:(

Sep 28, 2007

hello,
i have a Pictures table:  PictureID, Name, Description, DateAdded (GETDATE() when insert), IsActive...
i need to make some stored procedures to show me the pictures added in last 24hours, in last 3 days, last 2 weeks and so on
the pictures added in database are active (available to be seen by users) only 1yaer after the date added
I tryied to make a stored procedure (in fact i maked a lots of them, for 1day 3 days 1 week 1 month), but i have a problem with that DateDiff and DateAdd
Here is what i tryied CREATE PROCEDURE LastAdded_2monthsAgo

AS

SELECT Pictures.ProductID, Pictures.Name, Pictures.Description, Pictures.DateAdded
FROM Pictures
WHERE (DATEDIFF(month, Pictures.DateAdded, GETDATE()) >= 0) AND (DATEDIFF(month, Pictures.DateAdded, GETDATE()) <= 2)
ORDER BY DateAdded DescI have a feeling that is wrong, please make your own version and show me what i should write...I don't know what should be first the today date or the DateAdded...i need to select the last added products from a specific interval of time...Should i do something with that "1 year available" like  WHERE (DATEDIFF(month, GETDATE(), DATEADD(year, 1, Products.DateAdded)) >= 0) AND (DATEDIFF(month, GETDATE(), DATEADD(year, 1, Products.DateAdded)) <= 2) I am sure is a stupid thig up there...if you can, make your own version how you would do it and show me..please help me

View 5 Replies View Related

Using DateDiff Function For Age

Nov 12, 2007

Hi,I'm using the datediff function to display the ages of the users in my database. However the age rounds up once they are 35.5 etc...I could create another function which works similar to the DateDiff function, but use math.floor to always round down, but I need to use this function in a SQL statement WHERE clause. Is there any way around this?Thanks,Curt. 

View 3 Replies View Related

Sql Server DATEDIFF

Apr 25, 2008

This is a sql question, so I'm hoping someone can give me some direction.
I need to query a table and return all rows where the individual is >= 18 years of age. It should involve simply subtracting the date of birth from the current date.  I thought the answer would be so simple:
 select * from table where datediff(yy,dob,getdate()) >= 18
Unfortunately, the results are inconsistent.  The DATEDIFF function, it appears, will not show correct results down to the month/day level.  I tried posting this on a sql server forum, but the recommendations I received involved coding some gigantic function.  It seems that there ought to be a simple 'WHERE' clause which could solve this.
If someone knows of a silver bullet, I would surely appreciate your advice.
Thank you.

View 5 Replies View Related

DATEDIFF In A WHERE Clause

May 6, 2008

I'm trying to include a DATEDIFF compare in my Where clause, but it seems to ignore the comparison I'm trying to invoke, and just returns all  rows.  When I display the result of the DATEDIFF  command, it looks good, but I can't seem to have it incorporated in my Where clause.
The following is my code -
 select [Pkg ID], [Elm (s)], [Type Name (s)], [End Exec Date], [End Exec Time]
from pkgactions
WHERE (8 > DateDiff(year, [End Exec Date], GetDate() ))
order by [pkg id]
 
Thanks

View 4 Replies View Related

DATEDIFF Possibilities

Aug 10, 2004

Hi,

I have two fields in one of my database table. They are date fields, one for the start and the other for the end of the "problem solving". What I want to do is to show the concrete elapsed time between the two.

My first problem is that I'm not able to show hour AND minutes. I wrote this for instance:
SELECT DATEDIFF(hour, fld_date_debut, fld_date_fin) As elapsed_time
I tried HH:mm instead of hour, but it is not working.

My second problem is that I can have more than one start and end hour for the same "problem solving". In the database it's like:

start hour: 10:00 End hour: 11:00 Number of the problem: 1
start hour: 13:00 End hour: 16:00 Number of the problem: 1

So I would like to add these to my elapsed time. I want (11:00 - 10:00) + (16:00 - 13:00)...but how can i do this in my SQL query ?

Thanks.

View 1 Replies View Related

DateTime Using DateDiff

Dec 8, 2004

Hello everyone.

Im currently using the DateDiff function to filter my DateTime columns but am finding it somewhat troublesome. Currently I am having to write the same select statement 3 times if I want to filter by month, year or all (ignoring dates).

To find @PurchaseTotal for the year, I have to write the following:


SELECT
@PurchaseTotal = Sum(PurchaseTotal)
FROM
_Expenses
WHERE
DateDiff(yyyy, DateOf, @IntervalDate) = @Interval



To find @PurchaseTotal for a month, I have to write the following:


SELECT
@PurchaseTotal = Sum(PurchaseTotal)
FROM
_Expenses
WHERE
DateDiff(mm, DateOf, @IntervalDate) = @Interval



To find @PurchaseTotal for all the records, I have to write the following:


SELECT
@PurchaseTotal = Sum(PurchaseTotal)
FROM
_Expenses


I've tried the following code but I get an error.

DateDiff(@DateParameter, DateOf, @IntervalDate) = @Interval

Error says something like "incorrect parameter 1 for DateDiff."

It seems you have to write a different select statement for month, day and year. Also If you want a total from all the records you have to write yet another select statement.

Does anyone know of a DateTime function that allows parameters to specify for month, day and Year? Also does anyone know of a DateTime function that works like the COALESCE function to where you can send it a NULL value and give you all the records?

Thank you ahead for any direction you can give.


Alec

View 1 Replies View Related

DateDiff Always Return 0

Feb 14, 2006

I just discover the result for my query that had use the function dateDiff seems to be in-correct, no matter what's the date, the dateDiff always return a zero. Am I using it in-correctly?
select DateDiff(mm,11/1/2004, 12/31/2005)
SELECT component_id, component_description,SUM(CASE DateDiff(mm,date_complete,'12/31/2004')WHEN 2 THEN component_qty ELSE 0 END) AS mm1,SUM(CASE DateDiff(mm,date_complete,'12/31/2004')WHEN 1 THEN component_qty ELSE 0 END) AS mm2,SUM(CASE DateDiff(mm,date_complete,'12/31/2004')WHEN 0 THEN component_qty ELSE 0 END) AS mm3,sum(component_qty) as totalFROM view_jobcomponent WHERE date_complete between '10/1/2004' and '12/31/2004' GROUP BY component_id, component_descriptionorder by component_id, component_description

View 1 Replies View Related

Problems Using DateDiff

Jun 13, 2006

Hi im having som problems using the dateDiff,
1. Im not really sure what row's to grap,
2.Im getting this error saying somthing like  : "None-spicefied Function GetDate"
"sry for the bad translation, im getting the error's in danish and my englich is not to good :)"
Any help would be very nice =)
   -----------------------------------   Code   -----------------------------------
This is my clas.

Function NewSearch () As DataTable
Dim objData As New DataAccess


Dim strSQL As String = "SELECT datediff(mm, GetDate(), Repair) FROM Used_Cars"

Return objData.GetDataAccess(strSQL, _strDatabase)
End Function
 
And this is my default.aspx.vb .

Protected Sub action_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles action.Click
Dim Search As New carFactory
Dim dtMaerker As DataTable
dtMaerker = Search .NewSearch ()
      For Each Row As DataRow In dtMaerker.Rows
           ' "Repair" contains som date's
            lblIndhold.Text = Row.Item("repair") & "<br />"
      Next
End Sub

View 6 Replies View Related

Datediff Queries....?

Aug 19, 2000

hi gurus,

can anyone tell me how to write a query which you could use like a hotel wakeup call system with an email sent instead of a phone call. the fields in the table would only be the target email address and date/time of the event. i suspect the query would run on a 10 minute meta-refresh asp page containing the email broadcast app along with the query.

thanks
szazo

View 1 Replies View Related







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