Showing posts with label converted. Show all posts
Showing posts with label converted. Show all posts

Thursday, March 29, 2012

Converting datetime to integer and back

Hi all,

I have a problem converting datetime to integer (and than back to
datetime).
Depending whether the time is AM or PM, same date is converted to two
different integer representations, which holds as true on reversal
back to datetime.

AM Example:

declare @.DI integer; declare @.DD datetime
set @.DI = cast(cast('3/12/2003 11:34:02 AM' as datetime) as integer)
set @.DD = cast (@.DI as datetime)
print @.DI; print @.DD

Result:
37690
Mar 12 2003 12:00AM

PM Example:

declare @.DI integer; declare @.DD datetime
set @.DI = cast(cast('3/12/2003 11:34:02 PM' as datetime) as integer)
set @.DD = cast (@.DI as datetime)
print @.DI; print @.DD

Result:
37691
Mar 13 2003 12:00AM

Now, this is not a big problem if I knew that this is how it is
supposed to work. Is this how SQL Server is supposed to work?Nikola (nigel35@.hotmail.com) writes:
> AM Example:
> declare @.DI integer; declare @.DD datetime
> set @.DI = cast(cast('3/12/2003 11:34:02 AM' as datetime) as integer)
> set @.DD = cast (@.DI as datetime)
> print @.DI; print @.DD
> Result:
> 37690
> Mar 12 2003 12:00AM
> PM Example:
> declare @.DI integer; declare @.DD datetime
> set @.DI = cast(cast('3/12/2003 11:34:02 PM' as datetime) as integer)
> set @.DD = cast (@.DI as datetime)
> print @.DI; print @.DD
> Result:
> 37691
> Mar 13 2003 12:00AM
> Now, this is not a big problem if I knew that this is how it is
> supposed to work. Is this how SQL Server is supposed to work?

Apparently, SQL Server rounds to the nearest wholest int. I wouldn't
say this makes much sense to me.

Then again, I have to admit that I don't really see the point with
converting datetime values to integer.

In any case, the workaround should be simple, first chop of the
time portion.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Erland Sommarskog" <sommar@.algonet.se> wrote:
> Nikola (nigel35@.hotmail.com) writes:
> > AM Example:
> > declare @.DI integer; declare @.DD datetime
> > set @.DI = cast(cast('3/12/2003 11:34:02 AM' as datetime) as integer)
> > set @.DD = cast (@.DI as datetime)
> > print @.DI; print @.DD
> > Result:
> > 37690
> > Mar 12 2003 12:00AM
> > PM Example:
> > declare @.DI integer; declare @.DD datetime
> > set @.DI = cast(cast('3/12/2003 11:34:02 PM' as datetime) as integer)
> > set @.DD = cast (@.DI as datetime)
> > print @.DI; print @.DD
> > Result:
> > 37691
> > Mar 13 2003 12:00AM
> > Now, this is not a big problem if I knew that this is how it is
> > supposed to work. Is this how SQL Server is supposed to work?
> Apparently, SQL Server rounds to the nearest wholest int. I wouldn't
> say this makes much sense to me.
> Then again, I have to admit that I don't really see the point with
> converting datetime values to integer.
> In any case, the workaround should be simple, first chop of the
> time portion.

VB6 will allow a similar translation and it has the same problem: a real
number is returned where the fractional (i.e. right of the decimal point)
part represents the time. So, converting from datetime to an int carries a
hidden conversion that rounds to get the integer. Check this out (I used
money, although I assume float or real would suffice).

declare @.d datetime
declare @.n money

set @.d = '3/12/2003'
set @.n = convert(money, @.d)
print convert(varchar, @.n) + ' - ' + convert(varchar, @.d)

set @.d = '3/12/2003 11:34 AM'
set @.n = convert(money, @.d)
print convert(varchar, @.n) + ' - ' + convert(varchar, @.d)

set @.d = '3/12/2003 11:34 PM'
set @.n = convert(money, @.d)
print convert(varchar, @.n) + ' - ' + convert(varchar, @.d)

set @.d = '3/13/2003'
set @.n = convert(money, @.d)
print convert(varchar, @.n) + ' - ' + convert(varchar, @.d)

Craig|||Erland Sommarskog (sommar@.algonet.se) writes:
> Apparently, SQL Server rounds to the nearest wholest int. I wouldn't
> say this makes much sense to me.
> Then again, I have to admit that I don't really see the point with
> converting datetime values to integer.
> In any case, the workaround should be simple, first chop of the
> time portion.

Actually there is an even simpler workaround:

declare @.d datetime
declare @.i int

SELECT @.d = '20020202 11:59:00'
SELECT @.i = convert(float, @.d)
SELECT @.i

SELECT @.d = '20020202 12:01:00'
SELECT @.i = convert(float, @.d)
SELECT @.i

This works, because when convering from float to int, truncation occurs...

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

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

Sunday, March 25, 2012

Converting Access qrys with logical expressions

I'm upsizing an Access database. Got the data converted, working on
the front end, converting queries to views, but having trouble
converting queries that use logical expressions like the following:
SELECT OrderId,
Sum((BackOrderQtyAvailable>0)*-1) AS ReadyBackOrderItems
FROM OrderDetails
INNER JOIN Items
ON (OrderDetails.ClientId = Items.ClientId)
AND (OrderDetails.ItemId = Items.ItemId)
WHERE (NOT (SitesCustomerTypeId = 2
AND ExpressBackorder =True
AND OrderUrgency = 1 ))
GROUP BY OrderId;

Can someone suggest a strategy to achieve the same result, ie
OrderId,ReadBackOrderItems that I can use in further joins?

Thanks in anticipation
Terry Bell"Terry Bell" <dreadnought8@.hotmail.com> wrote in message
news:923537d6.0409142346.301c9c3@.posting.google.co m...
> I'm upsizing an Access database. Got the data converted, working on
> the front end, converting queries to views, but having trouble
> converting queries that use logical expressions like the following:
> SELECT OrderId,
> Sum((BackOrderQtyAvailable>0)*-1) AS ReadyBackOrderItems
> FROM OrderDetails
> INNER JOIN Items
> ON (OrderDetails.ClientId = Items.ClientId)
> AND (OrderDetails.ItemId = Items.ItemId)
> WHERE (NOT (SitesCustomerTypeId = 2
> AND ExpressBackorder =True
> AND OrderUrgency = 1 ))
> GROUP BY OrderId;
> Can someone suggest a strategy to achieve the same result, ie
> OrderId,ReadBackOrderItems that I can use in further joins?
> Thanks in anticipation
> Terry Bell

Are you asking how to rewrite the SUM expression? I don't know exactly what
the syntax above means, so this is a guess:

sum(case when BackOrderQtyAvailable > 0 then BackOrderQtyAvailable else 0
end * -1)

If this is wrong, then I suggest you post CREATE TABLE and INSERT statements
to create your tables and populate some sample data, along with the result
you expect to see from your query.

Simon|||"Simon Hayes" <sql@.hayes.ch> wrote in message news:<41480077$1_2@.news.bluewin.ch>...
> "Terry Bell" <dreadnought8@.hotmail.com> wrote in message
> news:923537d6.0409142346.301c9c3@.posting.google.co m...
> > I'm upsizing an Access database. Got the data converted, working on
> > the front end, converting queries to views, but having trouble
> > converting queries that use logical expressions like the following:
> > SELECT OrderId,
> > Sum((BackOrderQtyAvailable>0)*-1) AS ReadyBackOrderItems
> > FROM OrderDetails
> > INNER JOIN Items
> > ON (OrderDetails.ClientId = Items.ClientId)
> > AND (OrderDetails.ItemId = Items.ItemId)
> > WHERE (NOT (SitesCustomerTypeId = 2
> > AND ExpressBackorder =True
> > AND OrderUrgency = 1 ))
> > GROUP BY OrderId;
> > Can someone suggest a strategy to achieve the same result, ie
> > OrderId,ReadBackOrderItems that I can use in further joins?
> > Thanks in anticipation
> > Terry Bell
> Are you asking how to rewrite the SUM expression? I don't know exactly what
> the syntax above means, so this is a guess:
> sum(case when BackOrderQtyAvailable > 0 then BackOrderQtyAvailable else 0
> end * -1)
> If this is wrong, then I suggest you post CREATE TABLE and INSERT statements
> to create your tables and populate some sample data, along with the result
> you expect to see from your query.
> Simon

Thanks very much Simon you have given me the direction I needed.
For the record, here's my full converted code - with some side errors
fixed

SELECT Q845UndeliveredOrderDetails.OrderId, SUM(CASE WHEN
BackOrderQtyAvailable > 0 THEN 1 ELSE 0 END) AS ReadyBackOrderItems
FROM Q845UndeliveredOrderDetails INNER JOIN
Items ON (Q845UndeliveredOrderDetails.ClientId =
Items.ClientId) AND (Q845UndeliveredOrderDetails.ItemId =
Items.ItemId)
WHERE (NOT (SitesCustomerTypeId = 2 AND ExpressBackorder = 1 AND
OrderUrgency = 1))
GROUP BY Q845UndeliveredOrderDetails.OrderId;

So:
Sum((BackOrderQtyAvailable>0)*-1) AS ReadyBackOrderItems ... in Access
SQL
becomes
SUM(CASE WHEN BackOrderQtyAvailable > 0 THEN 1 ELSE 0 END) AS
ReadyBackOrderItems ... in SQL

I also note that in Access you can say something like

WHERE IsBackOrder

and it evaluates IsBackOrder as a logical expression
whereas in sql server we need to say

WHERE IsBackorder = 1

Is that right?

Then I guess I need to think about NULL too ...

Also I notice in the query analyser it comes up with a message saying
it can't understand the CASE statement, but I can ignore that, can I,
as it seems to go ahead and execute the query anyway?

Once again thanks a million this has saved me lots of time

Terry Bell|||<snip
> I also note that in Access you can say something like
> WHERE IsBackOrder
> and it evaluates IsBackOrder as a logical expression
> whereas in sql server we need to say
> WHERE IsBackorder = 1
> Is that right?

Not quite - there is no Boolean data type in MSSQL, so how to evaluate
'true' or 'false' depends on the data type you've chosen. One common
solution is to use the bit data type, with 1 for true and 0 for false, in
which case your code above is correct (assuming true = 1).

> Then I guess I need to think about NULL too ...

Yes - this is one reason why you often see requests for DDL (CREATE TABLE
etc.), as this makes it clear which columns allow NULL and which don't.
Something that seems to work fine may fail when NULLs are involved, so you
need to code for them if the data model allows them.

> Also I notice in the query analyser it comes up with a message saying
> it can't understand the CASE statement, but I can ignore that, can I,
> as it seems to go ahead and execute the query anyway?

I have no idea without seeing the full error, but perhaps this is error 8153
"Warning: Null value is eliminated by an aggregate or other SET operation."?
If so, it's just a warning that the column you SUMmed on contains NULL data.

> Once again thanks a million this has saved me lots of time
> Terry Bell

You're welcome.

Simon|||Generally just copy and paste from Access to Query Analyser. Check the
query runs correctly and then add CREATE PROCEDURE blah blah to the top
and run. This turns the script in to a stored procedure and loads it in
to the current database.

You might want to move all the restrictions to the WHERE clause other
wise you can get some interesting results if you are not very careful.

Sum((BackOrderQtyAvailable)* -1)

(BackOrderQtyAvailable > 0)

Adrian

Terry Bell wrote:
> I'm upsizing an Access database. Got the data converted, working on
> the front end, converting queries to views, but having trouble
> converting queries that use logical expressions like the following:
> SELECT OrderId,
> Sum((BackOrderQtyAvailable>0)*-1) AS ReadyBackOrderItems
> FROM OrderDetails
> INNER JOIN Items
> ON (OrderDetails.ClientId = Items.ClientId)
> AND (OrderDetails.ItemId = Items.ItemId)
> WHERE (NOT (SitesCustomerTypeId = 2
> AND ExpressBackorder =True
> AND OrderUrgency = 1 ))
> GROUP BY OrderId;
> Can someone suggest a strategy to achieve the same result, ie
> OrderId,ReadBackOrderItems that I can use in further joins?
> Thanks in anticipation
> Terry Bell|||On Thu, 16 Sep 2004 17:27:35 +0200, Simon Hayes wrote:
>"Terry Bell" <dreadnought8@.hotmail.com> wrote:
>>
>> Also I notice in the query analyser it comes up with a message saying
>> it can't understand the CASE statement, but I can ignore that, can I,
>> as it seems to go ahead and execute the query anyway?
> I have no idea without seeing the full error, but perhaps this is error 8153
> "Warning: Null value is eliminated by an aggregate or other SET operation."?
> If so, it's just a warning that the column you SUMmed on contains NULL data.

I don't think it's a null error -- I think he was editing his query in MS
Access's query editor, in an ADP file, rather than using SQL Server's Query
Analyzer. I've gotten that error from MS Access myself.

As Terry said, Access goes ahead and executes it anyway. It just can't
parse it properly to represent it in the graphical query editor.

Converting a type (e.g. Decimal) BEFORE writing to ResultSet ?

As well known a DATE or TIMESTAMP type can be converted (to VARCAHR) after s
election but BEFORE
writing to the ResultSet by using the CONVERT function e.g.
SELECT CONVERT(char(10), MYTIMESTAMP, 101)) FROM ... WHERE ...
Is there something similar if the original field is a DECIMAL/NUMERIC field?
E.g.
SELECT DEC_CONVERT(char(30), MYDECIMAL, '###########0.00') FROM .... WHERE
...
GeorgeGeorge Dainis wrote:
> As well known a DATE or TIMESTAMP type can be converted (to VARCAHR)
> after selection but BEFORE writing to the ResultSet by using the
> CONVERT function e.g.
> SELECT CONVERT(char(10), MYTIMESTAMP, 101)) FROM ... WHERE ...
> Is there something similar if the original field is a DECIMAL/NUMERIC
> field?
> E.g.
> SELECT DEC_CONVERT(char(30), MYDECIMAL, '###########0.00') FROM ....
> WHERE ...
> George
Just use CONVERT or CAST:
Select CONVERT(char(30), MyDecimal) From ...
Select CAST(MyDecimal as char(30)) From ...
David Gugick
Imceda Software
www.imceda.com|||You can also use function STR.
Example:
declare @.d decimal(8, 2)
set @.d = 50.25 / 2.00
select @.d, str(@.d, 8, 2)
go
AMB
"George Dainis" wrote:

> As well known a DATE or TIMESTAMP type can be converted (to VARCAHR) after
selection but BEFORE
> writing to the ResultSet by using the CONVERT function e.g.
> SELECT CONVERT(char(10), MYTIMESTAMP, 101)) FROM ... WHERE ...
> Is there something similar if the original field is a DECIMAL/NUMERIC fiel
d?
> E.g.
> SELECT DEC_CONVERT(char(30), MYDECIMAL, '###########0.00') FROM .... WHER
E ...
> George
>|||>From the documentation ... "CONVERT converts a character string from
one character set to another. The datatype of the returned value is
VARCHAR2." So what you are seeing is an implicit conversion to varchar2
because you are using a function that accepts a char as input.
Look at the functions TO_CHAR(), TO_DATE(), TO_NUMBER() and CAST() for
type conversion ...
http://download-west.oracle.com/doc.../b10759/toc.htm|||Oh that was strange ... I accessed the question through
comp.databases.oracle.misc but google tells me that the answer will get
posted to a sqlserver group? hmmm.|||On 16 Feb 2005 04:51:03 -0800, David Aldridge wrote:

>Oh that was strange ... I accessed the question through
>comp.databases.oracle.misc but google tells me that the answer will get
>posted to a sqlserver group? hmmm.
Hi David,
The orinal question was crossposted to a total of three groups:
* comp.databases.oracle.misc
* microsoft.public.sqlserver.programming
* comp.databases.oracle
The followup-to was set to only the SQL Server group. The use of CONVERT
in the original question suggests that this is indeed a SQL Server related
question. I have no idea why the original poster has included two Oracle
groups in his crossposting.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||"George Dainis" <george.dainis@.bluecorner.com> wrote in message
news:cuu58t$irh$04$1@.news.t-online.com...
> As well known a DATE or TIMESTAMP type can be converted (to VARCAHR) after
> selection but BEFORE
> writing to the ResultSet by using the CONVERT function e.g.
> SELECT CONVERT(char(10), MYTIMESTAMP, 101)) FROM ... WHERE ...
> Is there something similar if the original field is a DECIMAL/NUMERIC
> field?
> E.g.
> SELECT DEC_CONVERT(char(30), MYDECIMAL, '###########0.00') FROM ....
> WHERE ...
> George
>
Also well known are the TO_CHAR, ROUND, and TRUNC functions -- and don't
forget the CAST operator ;-)
++ mcs

Tuesday, March 20, 2012

Converted report too far against left side of screen

I converted an RS2000 report to RS2005 and uploaded it to a new 2005 Report Server.

When I view the report through IE 6 at the Report Server URL, the report seems jammed against the left side of the screen. This didn't happen when the report was in RS2000. When it was still an RS2000 report, there appeared to be some space (perhaps 1/8 - 1/4 inch) of space between the left edge of the screen and the left margin of the report.

Using Visual Studio 2005, I've tried moving all the objects within the report a little to the right, but that messes up the way the report prints.

Is this a common problem? Is there a way to get the space to the left of the report back when the report is rendered?

Thanks for your help!

Nancy

Also...

The border that used to be around the body of the report no longer shows up. I've checked the properties for the body of the report, and it is formatted to Border Color = Black, Border Style = Solid, and Border Width = 2pt. But the border no longer appears when the report is rendered.

sqlsql

Converted report loses border around report body

We have a (fairly large) number of reports that were created in RS 2000. We are trying to convert them to RS 2005.

All of these reports have a border around the report body. When I view the converted report in Visual Studio 2005, the border around the report body can be seen, but, when the report is rendered on the 2005 report server, the border around the report body disappears.

I've tried adding lines around the edges of the report body, but sometimes the right side line doesn't show up when the report is rendered, either.

I've seen questions about this on a few other sites, but no one seems to have an answer or workaround.

How do I get the border around the body of the converted reports (or lines around the body of converted reports) to reappear without having to completely rewrite over 50 reports?!?!?!?

Hi, I have the same problem.
Do you have solve it?
Thanks|||No one has a solution yet.

Converted data types

I'm using SQL Servers Import function to import an entire MS Access
database.
Date/time types from Access are defaulting to smalldatetime in SQL
Server, but the actual data is too large and I get an error, or rather
many errors since this happens in many tables.
I can edit the SQL to make these datetime types but, since there are
so many, is there any way to globally change the default data mapping?
What do you mean "the actual data is too large"? What "error" do you get?
Do you really have a lot of dates that fall outside the range supported by
smalldatetime?
Anyway, there is an easy way to generate a script to alter all smalldatetime
columns => datetime.
SELECT 'ALTER TABLE ['+TABLE_SCHEMA+'].[' + TABLE_NAME + '] ALTER COLUMN ['
+ COLUMN_NAME + '] DATETIME'
+ CASE WHEN IS_NULLABLE = 'NO' THEN
' NOT NULL ' ELSE '' END
+ CASE WHEN COLUMN_DEFAULT IS NOT NULL THEN
' DEFAULT ' + COLUMN_DEFAULT ELSE '' END + ';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'smalldatetime';
Aaron Bertrand
SQL Server MVP
http://www.sqlblog.com/
http://www.aspfaq.com/5006
"blindsey" <blindsey@.dsicdi.com> wrote in message
news:1183407383.413284.218870@.n2g2000hse.googlegro ups.com...
> I'm using SQL Servers Import function to import an entire MS Access
> database.
> Date/time types from Access are defaulting to smalldatetime in SQL
> Server, but the actual data is too large and I get an error, or rather
> many errors since this happens in many tables.
> I can edit the SQL to make these datetime types but, since there are
> so many, is there any way to globally change the default data mapping?
>

Converted data types

I'm using SQL Servers Import function to import an entire MS Access
database.
Date/time types from Access are defaulting to smalldatetime in SQL
Server, but the actual data is too large and I get an error, or rather
many errors since this happens in many tables.
I can edit the SQL to make these datetime types but, since there are
so many, is there any way to globally change the default data mapping?What do you mean "the actual data is too large"? What "error" do you get?
Do you really have a lot of dates that fall outside the range supported by
smalldatetime?
Anyway, there is an easy way to generate a script to alter all smalldatetime
columns => datetime.
SELECT 'ALTER TABLE ['+TABLE_SCHEMA+'].[' + TABLE_NAME + '] ALTER COLUMN ['
+ COLUMN_NAME + '] DATETIME'
+ CASE WHEN IS_NULLABLE = 'NO' THEN
' NOT NULL ' ELSE '' END
+ CASE WHEN COLUMN_DEFAULT IS NOT NULL THEN
' DEFAULT ' + COLUMN_DEFAULT ELSE '' END + ';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'smalldatetime';
--
Aaron Bertrand
SQL Server MVP
http://www.sqlblog.com/
http://www.aspfaq.com/5006
"blindsey" <blindsey@.dsicdi.com> wrote in message
news:1183407383.413284.218870@.n2g2000hse.googlegroups.com...
> I'm using SQL Servers Import function to import an entire MS Access
> database.
> Date/time types from Access are defaulting to smalldatetime in SQL
> Server, but the actual data is too large and I get an error, or rather
> many errors since this happens in many tables.
> I can edit the SQL to make these datetime types but, since there are
> so many, is there any way to globally change the default data mapping?
>

Converted data types

I'm using SQL Servers Import function to import an entire MS Access
database.
Date/time types from Access are defaulting to smalldatetime in SQL
Server, but the actual data is too large and I get an error, or rather
many errors since this happens in many tables.
I can edit the SQL to make these datetime types but, since there are
so many, is there any way to globally change the default data mapping?What do you mean "the actual data is too large"? What "error" do you get?
Do you really have a lot of dates that fall outside the range supported by
smalldatetime?
Anyway, there is an easy way to generate a script to alter all smalldatetime
columns => datetime.
SELECT 'ALTER TABLE ['+TABLE_SCHEMA+'].[' + TABLE_NAME + '] ALTER CO
LUMN ['
+ COLUMN_NAME + '] DATETIME'
+ CASE WHEN IS_NULLABLE = 'NO' THEN
' NOT NULL ' ELSE '' END
+ CASE WHEN COLUMN_DEFAULT IS NOT NULL THEN
' DEFAULT ' + COLUMN_DEFAULT ELSE '' END + ';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'smalldatetime';
Aaron Bertrand
SQL Server MVP
http://www.sqlblog.com/
http://www.aspfaq.com/5006
"blindsey" <blindsey@.dsicdi.com> wrote in message
news:1183407383.413284.218870@.n2g2000hse.googlegroups.com...
> I'm using SQL Servers Import function to import an entire MS Access
> database.
> Date/time types from Access are defaulting to smalldatetime in SQL
> Server, but the actual data is too large and I get an error, or rather
> many errors since this happens in many tables.
> I can edit the SQL to make these datetime types but, since there are
> so many, is there any way to globally change the default data mapping?
>

Converted Access database gives problems due to field names

Hi

I have been working with asp.net against an Access database (created by someone else several years ago). Now I have to move the database to run under MSSQL Server. I successfully updated it via the Access migration tool, and it's running fine under MSDE.

However, many of the fields in one table are 'named' as 'numbers' - eg 101, 102, 34 etc. Therefore SQL commands such as:

update Mytable set 101 = "test" where ID = 2

fail with Incorrect syntax near '101'.

I would never set up such a database structure myself, but I am stuck with it. Is there any way to make MSSQL commands work with this sort of naming?

Thanks for any help you can give.

LeeYou could try:


update Mytable set [101] = "test" where ID = 2

I have not tried this with fields that are all numbers, but I expect it should work.sqlsql

Monday, March 19, 2012

convert to set-based

I need help understanding this code and seeing if it can be converted to
set-based.
Declare @.Id int
Declare @.companyId numeric(18,0)
Declare @.franchiseId numeric(18,0)
--I understand this part where a table is created and populated
Declare @.tblCompanyFranchise Table( [Id] int, companyId numeric(18,0),
franchiseId numeric(18,0))
Declare @.pinId Varchar(30)
insert into @.tblCompanyFranchise([Id],companyId , franchiseId )
select [ID],numCompanyId,numFranchiseId from dbo.tblCompanyFranchise
where pinId is null
While(SELECT COUNT(*) FROM @.tblCompanyFranchise) > 0
Begin
--I don't understand where [id], companyid and franchiseid come from here to
compare to what is in the temp @.tblcompanyfranchise table
SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
@.tblCompanyFranchise
--here deleting row just selected above
DELETE FROM @.tblCompanyFranchise WHERE companyId=@.companyId
and franchiseId=@.franchiseId and [id] =@.id
--not sure purpose of attempts here
Declare @.attempts int
Set @.attempts = 10
while(@.attempts > 0)
Begin
--set @.pinid as unique
--not sure why add @.id to part of pinid
Set @.pinId = Abs(CheckSum(NEWID()))
Set @.pinId = cast ( (cast (substring(@.pinId,1,10-len(@.Id)) as varchar) +
cast (@.Id as varchar)) as Varchar)
--this part below I don't understand. Is the update statement at the bottom
outside of the if statement below? What is the purpose of the attempts? IF
the count is not > 0 then attempts are set to 0. Correct?
if((Select count(*) from dbo.tblCompanyFranchise where pinid = @.pinId) > 0)
Begin
Set @.attempts = @.attempts - 1
If @.attempts = 0
Set @.pinId = null
End
Else
Begin
Set @.attempts = 0
End
End
Update dbo.tblCompanyFranchise set pinId = @.pinId
where numCompanyId=@.companyId and numFranchiseId=@.franchiseId and [id] =@.id
End
Go
Is there a set-based way to do the same thing?Looks to me like it's trying to create a pin for each companyid, but it's
worried that the pin might not be unique. To combat that, they put the
companyid at the end of it, padding to 10 characters. I suppose then though,
they might have the situation where there are two pins the same, if the
companyids are, say, 102 and 3102.
I would suggest that the logic be investigated, and replaced with something
that is going to produce a unique string each time, so that it doesn't need
to do each one individually. For example, if you are allowed a pin of 30
characters (as per the declare statement), then why not use all 10
characters of the random number (pad it out if necessary) and then put the
id on the end. That way, there will never be an overlap, as the digits from
position 11 on would be unique (just longer for larger numbers).
If the pin has to be 10 characters, then perhaps you could put a hyphen in
before the companyid section?
If all the characters have to be digits, then perhaps pad the companyid out
to a known number of digits - but that will restrict the number of companies
you could have in the system.
Of course, the chance of an overlap is really quite small, so you could put
a unique index on the pinid field, and just retry the query if you get an
error.
update dbo.tblCompanyFranchise
set pinId = cast ( (cast (substring(cast(abs(CheckSum(NEWID())) as
varchar),1,10-len(Id)) as varchar) + cast (Id as varchar)) as Varchar)
where pinId is null
Rob
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:B80E4114-572B-4B03-9095-99BC70A780E3@.microsoft.com...
>I need help understanding this code and seeing if it can be converted to
> set-based.
> Declare @.Id int
> Declare @.companyId numeric(18,0)
> Declare @.franchiseId numeric(18,0)
> --I understand this part where a table is created and populated
> Declare @.tblCompanyFranchise Table( [Id] int, companyId numeric(18,0),
> franchiseId numeric(18,0))
> Declare @.pinId Varchar(30)
> insert into @.tblCompanyFranchise([Id],companyId , franchiseId )
> select [ID],numCompanyId,numFranchiseId from dbo.tblCompanyFranchise
> where pinId is null
> While(SELECT COUNT(*) FROM @.tblCompanyFranchise) > 0
> Begin
> --I don't understand where [id], companyid and franchiseid come from here
> to
> compare to what is in the temp @.tblcompanyfranchise table
> SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
> @.tblCompanyFranchise
> --here deleting row just selected above
> DELETE FROM @.tblCompanyFranchise WHERE companyId=@.companyId
> and franchiseId=@.franchiseId and [id] =@.id
> --not sure purpose of attempts here
> Declare @.attempts int
> Set @.attempts = 10
> while(@.attempts > 0)
> Begin
> --set @.pinid as unique
> --not sure why add @.id to part of pinid
> Set @.pinId = Abs(CheckSum(NEWID()))
> Set @.pinId = cast ( (cast (substring(@.pinId,1,10-len(@.Id)) as varchar) +
> cast (@.Id as varchar)) as Varchar)
> --this part below I don't understand. Is the update statement at the
> bottom
> outside of the if statement below? What is the purpose of the attempts? IF
> the count is not > 0 then attempts are set to 0. Correct?
> if((Select count(*) from dbo.tblCompanyFranchise where pinid = @.pinId) >
> 0)
> Begin
> Set @.attempts = @.attempts - 1
> If @.attempts = 0
> Set @.pinId = null
> End
> Else
> Begin
> Set @.attempts = 0
> End
> End
> Update dbo.tblCompanyFranchise set pinId = @.pinId
> where numCompanyId=@.companyId and numFranchiseId=@.franchiseId and [id]
> =@.id
> End
> Go
> Is there a set-based way to do the same thing?
> --
>|||I thought newid() always produced a unique value? Do you know what the
purpose of the 10 "attempts" toward the bottom was?
Thanks,
--
Dan D.
"Rob Farley" wrote:

> Looks to me like it's trying to create a pin for each companyid, but it's
> worried that the pin might not be unique. To combat that, they put the
> companyid at the end of it, padding to 10 characters. I suppose then thoug
h,
> they might have the situation where there are two pins the same, if the
> companyids are, say, 102 and 3102.
> I would suggest that the logic be investigated, and replaced with somethin
g
> that is going to produce a unique string each time, so that it doesn't nee
d
> to do each one individually. For example, if you are allowed a pin of 30
> characters (as per the declare statement), then why not use all 10
> characters of the random number (pad it out if necessary) and then put the
> id on the end. That way, there will never be an overlap, as the digits fro
m
> position 11 on would be unique (just longer for larger numbers).
> If the pin has to be 10 characters, then perhaps you could put a hyphen in
> before the companyid section?
> If all the characters have to be digits, then perhaps pad the companyid ou
t
> to a known number of digits - but that will restrict the number of compani
es
> you could have in the system.
> Of course, the chance of an overlap is really quite small, so you could pu
t
> a unique index on the pinid field, and just retry the query if you get an
> error.
> update dbo.tblCompanyFranchise
> set pinId = cast ( (cast (substring(cast(abs(CheckSum(NEWID())) as
> varchar),1,10-len(Id)) as varchar) + cast (Id as varchar)) as Varchar)
> where pinId is null
> Rob
> "Dan D." <DanD@.discussions.microsoft.com> wrote in message
> news:B80E4114-572B-4B03-9095-99BC70A780E3@.microsoft.com...
>
>|||>> s there a set-based way to do the same thing? <<
What is this nightmare of poorly formatted insanely proprietary code
supposed to do? Without a spec, it is pretty hard to answer your
querstion. I have the feeling that this crap is not using a relatioanl
key at all, but that it is randomly trying to construct an unverifiable
exposed locator on the fly.|||Dan,

>I thought newid() always produced a unique value?
It does. But your code isn't using it in its standard form. It's grabbing
its checksum, and its absolute value, so that just makes it a random number
less than 2^31.
But then you change the last characters of that number with the id from the
table. Eg... if you have an id of 100342, your 10-digit random number might
be:
2834100342
But the whole reason for doing it one by one is that your code is worried
that it might not be unique. But it's going to be _probably_ unique - the
only chance of overlaps is where you have two numbers that overlap already.
For example, there's a 1/1000 chance that the same number above could be
generated for company 4100342. And it figures that it should be able to find
a unique number some time in the first 10 tries - which it shouldn't have
any problem doing at all.
The chance of each one being unique is very high. Not high enough to warrant
doing each one individually and checking each time. But if you need it to be
enforced, then do it with a unique key, and just put a check in to see that
the update hasn't broken the rule. If it has, just re-run it.
Let's have a quick think about where the possible overlaps are:
Record 100342 could overlap with:
record 2 (1/1000000000 chance)
record 42 (1/100000000 chance)
record 342 (1/10000000 chance)
record 1100342 (1/1000 chance)
record 2100342 (1/1000 chance)
...etc
If there's a really good business reason for the uniqueness, this is enough
of a risk to make it worth enforcing, but you could update hundreds of
thousands of records at a time without noticing any overlaps.
Rob
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:F8787F1F-4AC0-405C-9E8E-5ACF7841F11D@.microsoft.com...
>I thought newid() always produced a unique value? Do you know what the
> purpose of the 10 "attempts" toward the bottom was?
> Thanks,
> --
> Dan D.
>
> "Rob Farley" wrote:
>|||The pinid column is a varchar(30) so if the contractor was really worried
about uniqueness, I don't know why he didn't use more of the id field. The i
d
itself is also supposed to be unique so the chance of combining the checksum
of newid() and all of the id field is pretty small.
I ran your query and it took 6 seconds. The original code took 4 hours.
Can you tell me what how this part of the code works:
SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
@.tblCompanyFranchise
I interpret it to mean select the first record from @.tblCompanyFranchise
where the @.id in @.tblCompanyFranchise equals [id] and where @.companyid equals
companyid and where @.franchiseid equals franchiseid. But where does the valu
e
for [id], companyid and franchiseid come from?
Thanks so much for your help Rob.
Dan D.
"Rob Farley" wrote:

> Dan,
>
> It does. But your code isn't using it in its standard form. It's grabbing
> its checksum, and its absolute value, so that just makes it a random numbe
r
> less than 2^31.
> But then you change the last characters of that number with the id from th
e
> table. Eg... if you have an id of 100342, your 10-digit random number migh
t
> be:
> 2834100342
> But the whole reason for doing it one by one is that your code is worried
> that it might not be unique. But it's going to be _probably_ unique - the
> only chance of overlaps is where you have two numbers that overlap already
.
> For example, there's a 1/1000 chance that the same number above could be
> generated for company 4100342. And it figures that it should be able to fi
nd
> a unique number some time in the first 10 tries - which it shouldn't have
> any problem doing at all.
> The chance of each one being unique is very high. Not high enough to warra
nt
> doing each one individually and checking each time. But if you need it to
be
> enforced, then do it with a unique key, and just put a check in to see tha
t
> the update hasn't broken the rule. If it has, just re-run it.
> Let's have a quick think about where the possible overlaps are:
> Record 100342 could overlap with:
> record 2 (1/1000000000 chance)
> record 42 (1/100000000 chance)
> record 342 (1/10000000 chance)
> record 1100342 (1/1000 chance)
> record 2100342 (1/1000 chance)
> ...etc
> If there's a really good business reason for the uniqueness, this is enoug
h
> of a risk to make it worth enforcing, but you could update hundreds of
> thousands of records at a time without noticing any overlaps.
> Rob
>
> "Dan D." <DanD@.discussions.microsoft.com> wrote in message
> news:F8787F1F-4AC0-405C-9E8E-5ACF7841F11D@.microsoft.com...
>
>|||I wish I knew. This project was contracted out. There was no statement of
work, documentation, etc. by the original contractors. The project was takin
g
too long (surprise!) so it was brought in-house and another group of
contractors was hired to fix it.
I look through the code once in a while to see how other people code and to
learn.
--
Dan D.
"--CELKO--" wrote:

> What is this nightmare of poorly formatted insanely proprietary code
> supposed to do? Without a spec, it is pretty hard to answer your
> querstion. I have the feeling that this crap is not using a relatioanl
> key at all, but that it is randomly trying to construct an unverifiable
> exposed locator on the fly.
>|||Dan,
It sounds to me like you need to look through the business rules, and
probably get new contractors. :) If you can use more than 10 digits, then by
all means do that. I would actually suggest starting with the id number and
then using the large number padded to 10 digits. That way, you can guarantee
its uniqueness, plus you won't have 0 as the first character (because you
will need to pad the 10-digits to be sure it's unique - consider the case
where your checksum gives you a very small result).

> Can you tell me what how this part of the code works:
> SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
> @.tblCompanyFranchise
This just gets the top row from @.tblCompanyFranchise without having any
filter, and populates the variables @.Id, @.companyId and @.franchiseId. It's
basically a cursor without having a cursor. My guess is that your
contractors have read that cursors are bad practice, but instead of taking a
set-based approach, have simply altered the code to remove the cursor
declaration.
Rob
PS: Sorry for my silence over the past several hours - I'm in Australia.
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:A69B97BF-8B5F-4BFE-AD9E-573868DBBAD7@.microsoft.com...
> The pinid column is a varchar(30) so if the contractor was really worried
> about uniqueness, I don't know why he didn't use more of the id field. The
> id
> itself is also supposed to be unique so the chance of combining the
> checksum
> of newid() and all of the id field is pretty small.
> I ran your query and it took 6 seconds. The original code took 4 hours.
> Can you tell me what how this part of the code works:
> SELECT TOP 1 @.Id=[id], @.companyId=companyId,@.franchiseId=franch
iseId FROM
> @.tblCompanyFranchise
> I interpret it to mean select the first record from @.tblCompanyFranchise
> where the @.id in @.tblCompanyFranchise equals [id] and where @.companyid
> equals
> companyid and where @.franchiseid equals franchiseid. But where does the
> value
> for [id], companyid and franchiseid come from?
> Thanks so much for your help Rob.
> --
> Dan D.
>
> "Rob Farley" wrote:
>|||:) Yup. I try to sleep at night occasionally.
"Stefan Berglund" <sorry.no.koolaid@.for.me> wrote in message
news:ges982dt67flvs05h9i7pjf0sja9ah6i0j@.
4ax.com...
> On Tue, 6 Jun 2006 11:46:47 +0930, "Rob Farley" <rob_farley@.hotmail.com>
> wrote:
> in <uVR#E9QiGHA.3904@.TK2MSFTNGP02.phx.gbl>
> Oh! - Have they been closed for several hours?
> --
> Stefan Berglund|||Yeah, we have a regular scheduled outage for maintenance. We shut down
the country for a few hours each night - didn't you get the memo?
*mike hodgson*
http://sqlnerd.blogspot.com
Stefan Berglund wrote:

>On Tue, 6 Jun 2006 11:46:47 +0930, "Rob Farley" <rob_farley@.hotmail.com>
>wrote:
> in <uVR#E9QiGHA.3904@.TK2MSFTNGP02.phx.gbl>
>
>Oh! - Have they been closed for several hours?
>--
>Stefan Berglund
>

Sunday, March 11, 2012

Convert to different date time format

Hi,
I want to convert following datetime value '2001-09-15 00:00:00.000'
to
'2001-09-15'
and the time part to be converted to respective 'AM, PM' Value
How can I do that?Better to do the formatting in the client side.
select
convert(varchar(10), getdate(), 126) + ' ' + right(convert(varchar(35),
getdate(), 109), 14)
go
AMB
"dotnettester" wrote:

> Hi,
> I want to convert following datetime value '2001-09-15 00:00:00.000'
> to
> '2001-09-15'
> and the time part to be converted to respective 'AM, PM' Value
> How can I do that?
>|||On Tue, 23 Aug 2005 13:57:01 -0700, dotnettester wrote:

>Hi,
>I want to convert following datetime value '2001-09-15 00:00:00.000'
>to
>'2001-09-15'
>and the time part to be converted to respective 'AM, PM' Value
>How can I do that?
Hi dotnettester,
http://www.karaszi.com/SQLServer/info_datetime.asp
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Thursday, March 8, 2012

Convert SQLExpress db to Sql Anywhere

Hi,

Is there any way that an existing database in SQL Express can be converted to a SQL Anywhere ?

regards

You can use the SQL Server Integration Services to move the data from SQL Express to SQL Server Everywhere. The links from the Online MSDN is as given below:

http://msdn2.microsoft.com/en-us/ms140269.aspx

http://msdn2.microsoft.com/en-us/ms141093(SQL.90).aspx

Thanks

Ambrish

|||

Hello Ambrish

Thanks for a quick response.

But honestly, didn't understand how to do it.

I have created a database using SQL Express 2005 and have a project (using VB 2005 Prof) fully working with this db. Since the release of SQL Everywhere, want to try out the same project by just creating / porting the sql express database to sql everywhere (both structure as well as data - atleast the structure)

regards

Dharam

|||

Hi Dharam,

SSIS transfers data table by table from a data source to SQL Mobile database. It does not transfer the schema. There are third party tools that transfers schema and data.

Jo?o Paulo Figueira has provided a link to a tool in the following post:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=484575&SiteID=1

Regards

Ambrish

Convert SQLExpress db to Sql Anywhere

Hi,

Is there any way that an existing database in SQL Express can be converted to a SQL Anywhere ?

regards

You can use the SQL Server Integration Services to move the data from SQL Express to SQL Server Everywhere. The links from the Online MSDN is as given below:

http://msdn2.microsoft.com/en-us/ms140269.aspx

http://msdn2.microsoft.com/en-us/ms141093(SQL.90).aspx

Thanks

Ambrish

|||

Hello Ambrish

Thanks for a quick response.

But honestly, didn't understand how to do it.

I have created a database using SQL Express 2005 and have a project (using VB 2005 Prof) fully working with this db. Since the release of SQL Everywhere, want to try out the same project by just creating / porting the sql express database to sql everywhere (both structure as well as data - atleast the structure)

regards

Dharam

|||

Hi Dharam,

SSIS transfers data table by table from a data source to SQL Mobile database. It does not transfer the schema. There are third party tools that transfers schema and data.

Jo?o Paulo Figueira has provided a link to a tool in the following post:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=484575&SiteID=1

Regards

Ambrish

Wednesday, March 7, 2012

Convert Seconds to hours:minutes:seconds

Hi all.

If I've got a query which has a field with seconds in it... how will I use
the Convert function to get my field converted to the format: HH:MM:SS ?

The field with the seconds in is called: "Diff"

Thanks alot

RudiI am not sure where this is correct way of finding

Try this

declare @.sec int
set @.sec=7612
select
convert(varchar(5),@.sec/3600)+':'+convert(varchar(5),@.sec%3600/60)+':'+convert(varchar(5),(@.sec%60))

Madhivanan|||On Wed, 9 Mar 2005 11:06:07 +0200, Rudi Groenewald wrote:

>If I've got a query which has a field with seconds in it... how will I use
>the Convert function to get my field converted to the format: HH:MM:SS ?
>The field with the seconds in is called: "Diff"

Hi Rudi,

You can use the suggestion Madhivanan proposes (that one will display
total hours, even if it's more than 24, but it will trim seconds and
minutes, leading to output like 11:5:3 instead of 11:05:03).

An other simple way (that will only work correct if the number of hours
is less than 24) is to use datetime logic:

SELECT CONVERT(char(8), DATEADD(second, Diff, '0:00:00'), 108)

If you need the ability to handle times > 24 hours, AND you want to
display 11:05:03 instead of 11:5:3, then you need to use a slightly more
complicated version of Madhivanan's suggestion:

SELECT CONVERT(varchar(6), Diff/3600)
+ ':' + RIGHT('0' + CONVERT(varchar(2), (Diff % 3600) / 60), 2)
+ ':' + RIGHT('0' + CONVERT(varchar(2), Diff % 60), 2)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)

Saturday, February 25, 2012

convert number to text

hi

can any one tell do we have any function to convert number to text.For example 25 to be converted to twenty five in SQLHello,

I'm working on it too... Still did not found a good solution though. Well, help would appreciated ! LOL

Thanks !|||Not sure why so many people ask the same question at once but see if my solution will help:

http://www.msdner.com/forum/thread586824.html

It could be expended if necessary...
Good Luck.

Friday, February 24, 2012

Convert mssql file

I am running mssql server for a sharepoint site. I have a mssql .bak file
that needs to be converted to plain text sql queries.
Is it possible to convert it somehow?
You have to restore it (in SQL Server) and query its with SQL Server or pump
the data out to some more propetary format liek access.
HTH, Jens Suessmeyer.
"Nick Mirro" <dirdx@.comcast.net> schrieb im Newsbeitrag
news:utFWDpuVFHA.3488@.TK2MSFTNGP10.phx.gbl...
>I am running mssql server for a sharepoint site. I have a mssql .bak file
>that needs to be converted to plain text sql queries.
> Is it possible to convert it somehow?
>

Convert mssql file

I am running mssql server for a sharepoint site. I have a mssql .bak file
that needs to be converted to plain text sql queries.
Is it possible to convert it somehow?
You have to restore it (in SQL Server) and query its with SQL Server or pump
the data out to some more propetary format liek access.
HTH, Jens Suessmeyer.
"Nick Mirro" <dirdx@.comcast.net> schrieb im Newsbeitrag
news:utFWDpuVFHA.3488@.TK2MSFTNGP10.phx.gbl...
>I am running mssql server for a sharepoint site. I have a mssql .bak file
>that needs to be converted to plain text sql queries.
> Is it possible to convert it somehow?
>

CONVERT Money Char(20)

I have a sql query listed below that I would like to only output values like
'6024', the Bonus values are converted to char(20) from Call_Movement table.
SELECT cast(cast(Bonus as money) as char(20)) like = '6024' from
Call_Movement
where DATEDIFF(mi, Start_Time, GETDATE()) <=60
Please help me complete this task.Joe K. wrote:
> I have a sql query listed below that I would like to only output values like
> '6024', the Bonus values are converted to char(20) from Call_Movement table.
>
> SELECT cast(cast(Bonus as money) as char(20)) like = '6024' from
> Call_Movement
> where DATEDIFF(mi, Start_Time, GETDATE()) <=60
> Please help me complete this task.
Please post with table structure and simple data and desired output.
if you are not using wildcard then no need to use like in the query
just use =.
Also you can not put = after like and you have to put like operator in
where clause.
Regards
Amish Shah

CONVERT Money Char(20)

I have a sql query listed below that I would like to only output values like
'6024', the Bonus values are converted to char(20) from Call_Movement table.
SELECT cast(cast(Bonus as money) as char(20)) like = '6024' from
Call_Movement
where DATEDIFF(mi, Start_Time, GETDATE()) <=60
Please help me complete this task.Joe K. wrote:

> I have a sql query listed below that I would like to only output values li
ke
> '6024', the Bonus values are converted to char(20) from Call_Movement tabl
e.
>
> SELECT cast(cast(Bonus as money) as char(20)) like = '6024' from
> Call_Movement
> where DATEDIFF(mi, Start_Time, GETDATE()) <=60
> Please help me complete this task.
Please post with table structure and simple data and desired output.
if you are not using wildcard then no need to use like in the query
just use =.
Also you can not put = after like and you have to put like operator in
where clause.
Regards
Amish Shah

Friday, February 10, 2012

Convert Date and order by

Hi!

I have a little problem. I'm trying to sort a date I have converted like this
Convert(datetime,LH.LoginDateTime,103) as RegistrationDate

But when I use Order by on RegistrationDate it only sort on days:

01/11/2006
01/12/2006
02/11/2006
02/12/2006
03/11/2006
03/12/2006

I'll guess it's because of the "varchar" convert, but I need the date to bee inn this format, since I only shall check the date and not the time. Is there a way around this, so I can order it like this? (Se under)

01/11/2006
02/11/2006
03/11/2006
01/12/2006
02/12/2006
03/12/2006

Sample SQL;

select Convert(varchar,LH.LoginDateTime,103) as RegistrationDate,
select count(*) from LoginHistory AS LH2 where datepart(hh,LH2.LoginDateTime)<7 AND
Convert(varchar,LH2.LoginDateTime,103)>=Convert(varchar,LH.LoginDateTime,103) AND
Convert(varchar,LH2.LoginDateTime,103)<=Convert(varchar,LH.LoginDateTime,103))
As beforehour07
from LoginHistory AS LH
where LH.LoginDateTime >='''+ Convert(varchar,@.FromDate,113) + ''' ' +
'and LH.LoginDateTime <='''+ Convert(varchar,@.ToDate,113) + ''' ' +
'group by Convert(varchar,LH.LoginDateTime,103)'
Order by RegistrationDate

Hi there,

Why dont you just order by the LH.LoginDateTime field?

thanks,

Murthy here

|||

You should also look on your count select statement because it will not work correctly comparing strings not dates, try this if you would like to use days only without time:

select Convert(varchar,LH.LoginDateTime,103) as RegistrationDate,
(select count(*) from LoginHistory AS LH2 where datepart(hh,LH2.LoginDateTime)<7 AND
convert(datetime,Convert(varchar,LH2.LoginDateTime,103))>=convert(datetime,Convert(varchar,LH.LoginDateTime,103)) AND
convert(datetime,Convert(varchar,LH2.LoginDateTime,103))<=convert(datetime,Convert(varchar,LH.LoginDateTime,103)))
As beforehour07
from LoginHistory AS LH
where LH.LoginDateTime >='''+ Convert(varchar,@.FromDate,113) + ''' ' +
'and LH.LoginDateTime <='''+ Convert(varchar,@.ToDate,113) + ''' ' +
'group by Convert(varchar,LH.LoginDateTime,103)'
Order by convert(datetime,RegistrationDate)

or you can try to rewrite your query to work much faster with single join instead of multiple internal queries to do counts.

This one will kill your server if you will try to process table with thousands of records

|||Thanks for the answer!

If I order by LH.LoginDateTime, I have to select from LH.LoginDate and group by LH.LoginDate or else I get the error:
"Column "LoginDateTime" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause." since the?dates don't match anymore.

If I put LH.LoginDateTime in the select,group and Order by, the dates on the same day won't match so the group by won't hit. I will get a new row for every hit on the same day like this:

01.11.2006 00:11:40
01.11.2006 00:15:41
01.11.2006 00:15:44
01.11.2006 00:16:48

I need to convert the date to dd/mm/yyyy(or something like that, removing the time) and be able to group and then order it. Do you or anyone know if it's possible?Smile

Murthy Puvvada:

Hi there,

Why dont you just order by the LH.LoginDateTime field?

thanks,

Murthy here?

|||Fixed it, I could use cast(floor(cast(LH.LoginDateTime as float)) as datetime) to sett the time to 00:00:00