Dealing With Datetime And SQL Transact-SQL

Apr 4, 2007

I am trying to make a stored procedure in SQLServer Express.
The question is related to this stored procedure / transact - sql.
 I think i am doing something wrong with datetime.
Here is the stored procedure.
The error i am getting is that:
Msg 241, Level 16, State 1, Line 20
Syntax error converting datetime from character string.

 ===================================== 
DECLARE    @websiteID  int
DECLARE    @dateFrom  datetime
DECLARE    @dateTo  datetime
DECLARE    @sortbystring  varchar (20)

set @websiteID = 1
set @dateFrom = Convert(datetime, '2007-02-07 12:01:00')
set @dateTo  = Convert(datetime, '2007-03-07 11:59:00')
set @sortbystring = 'Campaign'

IF ISNULL(@dateTo, '') = ''
begin
    SET @dateTo = @dateFrom
end

SET @dateTo = DATEADD(d, 1, @dateTo)

DECLARE @str CHAR(400)

LINE 20: SET @str = 'SELECT dateEntry, c.name as Campaign, e.firstname as FirstName FROM entry e, campaign c WHERE e.campaignID = c.id ' + 'AND c.websiteID = @websiteID' + 'AND (ISNULL(' + @dateFrom + ', '''') = '''' OR e.dateEntry BETWEEN '' + @dateFrom + '' AND '' + @dateTo + '') ' + 'AND e.IP NOT IN (SELECT IP FROM IP) ' + ' ORDER BY dateEntry DESC'
print (@str)


=============================================== 

View 9 Replies


ADVERTISEMENT

Dealing W/ Minutes In DateTime Field

Apr 16, 2004

If I subtract 14 days from a datetime field, will the time of day that I run this query affect the resultset? I am running the query during "normal business hours", 8 am - 5 pm, and the records are entered during this time frame as well.

ddave

View 6 Replies View Related

Transact SQL :: Difference Between Datetime In One Row And Datetime In The Row Above

May 21, 2015

I have a table that has a unique ID and a datetime of when something changed.

See example:
ID    TimeStamp
16094    2013-11-25 11:46:38.357
16095    2013-11-25 11:46:38.430
16096    2013-11-25 11:46:38.713
16097    2013-11-25 11:46:38.717
16098    2013-11-25 11:46:38.780

[Code] ....

Is there a way I can calculate the difference between row 16106 and 16105 and enter it in line 10601.

View 10 Replies View Related

Transact SQL :: Calculate DateTime Column By Merging Values From Date Column And Only Time Part Of DateTime Column?

Aug 3, 2015

How can I calculate a DateTime column by merging values from a Date column and only the time part of a DateTime column?

View 5 Replies View Related

Transact SQL :: CAST 0 As DateTime

Apr 14, 2015

How do you cast 0 as DateTime?  Is this possible to do.I am using UNION to combine two tables.  I get an error when doing so...

Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date
SELECT TOP (100) PERCENT
Opportunity_Name
,Status
,Closed_Status

[code]....

I understand what is causing the error.  In the top select statement both Closed_Status AND Expected_Close_Date are datetime values.  But in the bottom statement they are int.  

I understand what is causing the error.  In the top select statement both Closed_Status AND Expected_Close_Date are datetime values.  In the bottom statement they are int.  So I tried CASTing them as datetime, that didn’t work and I get this error.<o:p></o:p> Conversion failed when converting the varchar value 'Open' to data type int.Is there a way to CAST 0 as a DateTime

View 6 Replies View Related

Transact SQL :: Convert Datetime To Integer?

Aug 5, 2013

I have this datetime: '2002-12-20 11:59:59'

I want to convert this to date (yyyy-mm-dd) to integer

This works fine for: SELECT CONVERT(INT, GETDATE())

But it doesn't work here: SELECT CONVERT(INT, '2002-12-20 11:59:59')

I want to convert date to integer without passing through any varchar conversion/result.

View 6 Replies View Related

Transact SQL :: Populating A Datetime Column

Apr 29, 2015

I want to populate a datetime column on the fly within a stored procedure. Below is the query that I currently have that does same but slows down query performance.

CREATE TABLE #TaxVal
(
ID INT
, PaidDate DATETIME
, CustID INT
, CompID INT

[code]...

Which is the best way to write this query for better performance?

View 2 Replies View Related

Transact SQL :: Convert String To Datetime

Jul 28, 2015

I have below string, which is a datetime value

I want to convert it into datetime data type and insert into table

DECLARE @Date VARCHAR(100)

SET @Date='10312013122642'

View 8 Replies View Related

Transact SQL :: Insert Into With Cast Datetime

Aug 10, 2015

I am trying to automate a load of insert cmd but some of them contain date times so i am trying to insert the following but keep getting

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

What is wrong with the cmd??

INSERT INTO client VALUES (100, NULL, NULL, NULL, NULL, 1, NULL, 0, 0, 0, 0, 0, NULL,Cast( '2013-03-11 10:54:46.529' as datetime))

View 11 Replies View Related

Transact SQL :: Round Off Timestamp In DateTime To 11:00 Or 23:00

Oct 5, 2015

I have a datetime stamp and I want to round off the the time to 11:00 if the timestamp is between 5AM and 5PM. If it is beyond then round off to 23:00. I don't use date I only use timestamp in my query so I just want to round off the timestamp. Is there is function to do that.

View 3 Replies View Related

Transact SQL :: How To Convert CCYYMMDDHHMMSS To Datetime Format

Aug 20, 2015

I have a data column coming in from a 3rd party vendor in the format of CCYYMMDDHHMMSS. How can I convert this data to a [datetime] format?

CAST(CAST([TransactionDate] AS CHAR(14)) AS datetime)

Is that correct?

View 7 Replies View Related

Transact SQL :: Get Week Number From DateTime Field?

Aug 21, 2015

Any easier way to do what I am trying, without having a table with all the dates and week numbers.

Scenario: Week number of a DateTime Field where the year does not start on January 01<sup>st</sup> but April 1<sup>st</sup> to 31 Mach.

Issue: A week always starts on a Monday so if the 1<sup>st</sup> is on Tuesday, the first week is Tuesday – Sunday, if the 1<sup>st</sup> April is on Friday, the 1<sup>st</sup> week is Friday – Sunday and 7 day periods from there.

CREATE
TABLE [dbo].[DailyCanx](     
[ID] [int] IDENTITY(1,1)
NOT NULL,     
[DateCancelled] [datetime] NULL
)
ON [PRIMARY]

[code]....

I could create a table with all the start date and end dates of all the week numbers but I think there must be a better way. using SQL Server 2008 R2.

View 5 Replies View Related

Transact SQL :: Query DateTime Field By Date Range

Dec 2, 2015

I have a table of errors with a DateTime field for when the error occurred.  I want to query the table for a given date range omitting the time portion.  What is the most efficient way to perform this query?

View 5 Replies View Related

Transact SQL :: Convert Int To Time And Concatenate It With Datetime Field?

Sep 16, 2015

I have a datetime field for e.g 2015-09-15 00:00:00.000 and an integer field for e.g.100809.

The integer field is actually a time value as in hours,minutes,seconds. For e.g. the value

100809 means
10-hours
08-minutes
09-seconds

I need to combine the datetime and the int field to get the output as below

2015-09-15 10:08:09

View 7 Replies View Related

Transact SQL :: Get Only Newly Inserted Rows By Datetime Column?

Aug 17, 2015

I have a TableA where data get inserted from Excel(IMPORT/EXPORT wizard)

TableA;
ID(identity)   Date (NOT NULL Defaulyt Getdate() )                          
 Name            Phone
1                   2014-06-17 17:28:21.190          
Nick              12345678910
2                  2014-05-17 17:28:21.190        
 Stan              00045678910
3                  2015-08-17 17:28:21.190        
 Kim                 11111678910
4                  2015-08-17 17:28:21.190          
Tom                NUll 

 3,4 are the rows i have inserted now , you can see by date, likewise i have 100,000 rows(old and new combination) and now the data from excel to TableA can be imported/exported daily , hourly, weekly basis.

Now i want to find out only the rows which are imported to tableA today, or hours back, or yesterday .....

 the reason is , 

Step1:get data from excel and import to tableA( this is a manual Step) and i know when the data is inserted  with exact date and time.

Step2: get newly inserted rows from TableA and pass them as Parameters in Stored Procedure.( i may run step 2 after 1 hour, or after  1 day or after 1 week ,but i want only rows that are inserted ) 

I tried with using where Datecreated, but did work.

View 4 Replies View Related

Transact SQL :: Sorting By Minimum Of Multiple DATETIME Columns

Apr 22, 2015

I have a view in my database detailing the expiry date of each credential for each employee. The view is designed as to display one record per employee and in that record is the expiry date of each credential and the days remaining. So the columns are as follows:-

Employee CodeExpiry Date (x8 columns) (named as credential e.g. [Passport])
Days Remaining (x8 columns) (named as "TS_" + Credential)

I'm trying to use the CASE function to compare each DATETIME column with one another and retrieve the minimum. How can I return the minimum date as a run-time column and sort the view by this column? My code is as follows:-

SELECT [Passport],[TS_Passport],[Visa],[TS_Visa],[Civil_ID],[TS_Civil_ID],[KOC_Pass],[TS_KOC_Pass],[JO_Pass],[TS_JO_Pass],
[Ratqa_Pass],[TS_Ratqa_Pass],[Driving_License],[TS_Driving_License],[Health_Book],[TS_Health_Book], CASE
WHEN Passport <= Visa AND Passport <= Civil_ID AND Passport <= KOC_Pass AND Passport <= JO_Pass AND

[code]....

I've been told that this is the most efficient given the number of records in my database. The Min_Date is always NULL. I need the minimum of the 8 dates to be the Min_Date.

View 9 Replies View Related

Transact SQL :: Split Rows By Day / By Datetime And Partition By Columns

Jul 22, 2015

I am trying to spilt records into days by the start - End datetime.

I would send an image and data but because I am new to the forum, I am blocked sending images.

"Body text cannot contain images or links until we are able to verify your account"

How I can forward an image.

View 15 Replies View Related

Transact SQL :: Updating Date Part In Datetime Column

Sep 18, 2015

I need to set only the date part of tblEventStaffRequired.StartTime to tblEvents.EventDate while maintaining the time part in tblEventStaffRequired.StartTime.

UPDATE tblEventStaffRequired
SET StartTime = <expression here>
FROM tblEvents INNER JOIN
tblEventStaffRequired ON tblEvents.ID = tblEventStaffRequired.EventID

View 4 Replies View Related

Transact SQL :: Use Date / Hour And Minute In Datetime Column Type?

Nov 9, 2015

I just need the date, hour, and minute...not the micro seconds. Do I have to DATEPART and concatenate each or is there any way to simply truncate the milliseconds from it? Or is there a date format to put extract and report on it as...

MM/DD/CCYY HH:MM:SS AM

I see there is a format 131 that puts it in..

DD/MM/YYYY HH:MM:SS:MMMAM

View 7 Replies View Related

Transact SQL :: Only Store Datetime Values Down To Nearest Minute Automatically Without Using Trigger

Sep 25, 2015

Is there a way that I can do this at the table level to automatically handle the rounding of seconds, etc. down to the minute automatically without having to use a trigger?  

Here is a very basic example of what I am trying to do:

--example:  '09-22-2007 15:07:18.850' this is the value inserted into the table by the code
select getdate() 

 --example: '2007-09-22 15:07:00.000'  this is the value I want to store in the table
select dateadd(mi, datediff(mi, 0, getdate()), 0)

View 24 Replies View Related

Transact SQL :: Query Fails To Retrieve Full Dataset Using Datetime After Successful Execution Of SSIS Package?

Jun 16, 2015

I have an SSIS Package which Retreives Data using a  SQL Query like below 

select  a.* from dbo.test a (nolock)
JOIN dbo.test1 b (nolock)
ON a.DetailsId = b.DetailsId
JOIN dbo.test c (nolock) on c.DetailsLineId = b.DetailsLineId
where convert(date,c.CpPlacedDate)>?
and convert(date,c.CpPlacedDate)  < convert(date,GETDATE()) 
and c.PartnerCode in ('akakak07')

The CpPlacedDate DataType is Datetime. After the Successfull Execution of SSIS Package the final output results in destination is lesser than source.  

The Maximum of cpplaceddate in the Destination for a particular date is '2015-06-13 23:46:08.923'

The Maximum of cpplaceddate in the Source for a particular date is '2015-06-13 23:59:14.873' 

I am missing 16 records in between this time Gap.

View 3 Replies View Related

Dealing With DBNull

Jan 10, 2008

Hello!
Is there an easy way to deal with this situation below when reading in data from a SQL Database:
int? myNullableColumn;myNullableColumn = Convert.ToInt32(datarow["datacolumn"]);
 
Where, ideally, 'myNullableColumn' would be 'null' if the value was 'DBNull.Value'.  This does not work because Convert.ToInt32 will not convert 'DBNull.Value to null', but instead throws an error.
Is there a built in funtion that does do this?
Thanks!

View 8 Replies View Related

Dealing With Dups And A Lot More!

Mar 14, 2008

Ok, I have a table with about 47000 records in it. I have the following query for that table:Select ReportType =
Case
When ReportType = 1 Then 'Uniquery Report'
When ReportType = 2 Then 'SABRE Report'
When ReportType = 3 Then 'Menu Report'
Else Null
End,
ReportNameTo_,
Frequency.Frequency as Frequency,
ReportDate,
ReportDescription
From Report
Inner Join Frequency on ( Report.ReportFrequency = Frequency.FID )
Where ( Active = 1 )
And ReportDate = ( Select Max ( ReportDate ) From Report Where ( Active = 1 ) )
And ReportID = ( Select Max ( ReportID ) From Report Where ( Active = 1 ) )  
The idea is that i need to get only the last report based off of unique reportname. I added a computer column to the table to give me the ReportNameTo_, since my deliminator is the _. Now my issue is that I have 1 records showing (the last record added to the table), which is right for the query that is written, but wrong for what I want. I need to only return the last record for each unique ReportNameTo_. So as an example, my table has the following ID, ReportNameTo_, Date fields the data looks something like this:
1, 123_, 1/1/20082, 123_, 1/1/20083, 124_, 1/1/20084, 124_, 1/1/20085, 125_, 1/1/20086, 125_, 1/1/20087, 126_, 1/1/20088, 126_, 1/1/2008
I only want to return the following:
2, 123_, 1/1/20084, 124_, 1/1/20086, 125_, 1/1/20088, 126_, 1/1/2008
Hope someone out there can let me know how to do this... I am almost there, just not all the way.

View 2 Replies View Related

Dealing With Duplicates

Feb 15, 2002

Hello!
Just looking for advise on dealing with duplicates in database.
I have a contact table that have a bunch of duplicated customer records.
My goal is to combine all duplicated records into one record.
This involves couple tables:contact,contact history ,calendar.
All tables related by common column "accountno".
What would be the best approach for this?

Thank you,
Lena

View 2 Replies View Related

Dealing With Nulls

Mar 15, 2002

I have the following query in a stored procedure. If there are no rows in the history file, it returns a null. If there some setting or function that would have it return a zero if no rows are found? I use the variable to do arithmetic later on and a null messes everything up.

select@MarketTotal = sum(isnull(MarketValue,0))
fromhistory
whereEmpUID = @EmpUID and
Shares > 0

Thanks,
Ken Nicholson

View 2 Replies View Related

Dealing With NULLs

Jun 9, 2006

Hi i have the following :

select agent, name, surname, address, cust1_text01, cust1_text02, phone1,
case call_type_id
*when NULL then ''
else call_type_id
end as 'call_type_id'
from Record_T

* I have also tried when NULL then space(1)

yet the query still returns NULL when this field is empty ?
the idea is to always return data, even if the field is NULL to
replace it with an empty space or spaces.

View 3 Replies View Related

Dealing With Two Databases

Sep 28, 2007



Hello,

Question 1:
In my senario i've developed a system which utilizes 2 database, i've writen queries like db1.dbo.table1 join db2.dbo.table2 etc... Now that db2 is getting huge, client wants to shift it to another server.
I don't know how to modifiy my queries to cope with such situation. Could somebody plz tell me on how to you write queries involving two databases from different servers.

Question 2:

I'm maintaining second database (db2) to keep track of records of db1 which have been processed by my software, so that when db1 gets added with more records i can compare db2 table with db1 table to identify which records are new.
db1 is not my database and i don't have any control over that, (it's some erp db), is there any way of identifying which rows have been processed. Can the need for db2 be eliminated?


I'm using SQL Server 2005

Thank You,
Sandeep.

View 1 Replies View Related

Transact SQL :: Update Time Portion Of DateTime Field With Time Parameter

Oct 3, 2015

I hope to update a DateTime column value with a Time input parameter.  Poor attempt below but it looks like the @ApptTime param is coming in as 10:45:00.0000000 and I might have an existing @SendOnDate as: 2015-10-05 07:00:00.000...I hope to end up with 2015-10-05 10:45:00.000

ALTER PROCEDURE [dbo].[SendEditUPDATE]
@QuePoolID int=null
,@ApptTime time(7)
,@SendOnDate datetime

[code]...

View 14 Replies View Related

Dealing With Null Values

Jul 31, 2006

hi ive got a inert sub where i grab values from text boxes etxthe values are passed to a stored procedure however , one of these fields is a date field , but the field is not required ...so on this line if the date text box is left blank i get an error , not a valid date    .Parameters.Add("@actiondate", SqlDbType.DateTime).Value = txtActionDate.Texti have tried ( the actiondate field can take nulls ..)if txtActionDate="" then    .Parameters.Add("@actiondate", SqlDbType.DateTime).Value = nothing else.Parameters.Add("@actiondate", SqlDbType.DateTime).Value = txtActionDate.Textend if but this doesnt workwhat is the best way of allowing blank values to be passed to the stored procedure( it doesnt fall over with normal text / varchar fields ) thanks

View 1 Replies View Related

Questions Dealing With Performance

Dec 16, 2004

I have a stored procedure that takes less than 1 second in sql query analyzer to return my results.
I run this same SP in ASP.NET using a calendar control and using perf monitor I notice that for me from my dev machine my cpu utilization is sometimes over 40%.Is there any tweaks I can do to help decrease CPU utilization.

View 2 Replies View Related

Dealing With Optional Variables

Jan 23, 2004

I'm looking for opinions here:

I have a stored procedure that has one required variable, and two optional variables, like this:

CREATE PROCEDURE sp_tariff_rule
@tariff_id INT,
@start_date DATETIME = NULL,
@end_date DATETIME = NULL
...etc...

I want the procedure to process
1) all data is no dates are presented
2) all data after the start date, if no end date is supplied
3) all data before the end date if no start date is supplied
4) all data between the start and end dates if both are supplied

Now, instead of an elaborate conditional, I added this to the WHERE clause of my SQL statement:

AND ((@start_date IS NULL OR service_date >= @start_date) AND (@end_date IS NULL OR service_date <= @end_date))

It works fine, but I want to know if anyone has a different/better way of doing it, or if there is a big bug waiting to happen here.

I typically don't like to create multipurpose routines in my code, but this is a better approach for my in a non-object-oriented world of SQL.

View 1 Replies View Related

Dealing With More Than 8000 Characters

Nov 14, 2005

In SS 2000 it seems that there is no variable data type that can hold more than 8000 characters (varchar) or 4000 unicode characters (nvarchar). I've seen posts where multiple variables are spliced together to extend this limit. I am looking at performing string manipulations in an sproc and I need to be able to deal with the full 2GB/1GB limit of text and ntext field types. Is this possible? How do you deal with that?

View 14 Replies View Related

Dealing With 's In Insert Statements

May 31, 2007

Hello all. Got bit of a long winded question here...........so here we go lol.

OK.......ive got data on an Excel spreadsheet. Ive set the spreadsheet up as a linked server and i'm creating a set of insert statements from it by using the following code:


SELECT 'INSERT INTO TRAINREC (COURSE_NAME) VALUES ('''+
EMPLOY_REF + ''', '''+

FROM AtriumDD...['Employee Training Records$']


For most records this generates a correct insert statement.........for example:


INSERT INTO TRAINREC (EMPLOY_REF, COURSE_NAME) VALUES ('153', 'NMA Panel');


However.........my problems start when the value for course name is containes an ' character. If it does the insert statement generated is incorrect. For example:


INSERT INTO TRAINREC (EMPLOY_REF, COURSE_NAME) VALUES ('139', 'Annual Accounting in Lloyd's Market');


can anyone suggest any ideas on how to get round this? Also if i havent explained it clearly enough just let me know and i can try and expand on it.

Thanks for reading.

View 5 Replies View Related







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