Order By Case Cast Convert Error

Jul 23, 2005

I have created a SQL Stored Procedure that uses a Case statement to
determine the Order By. For one of the Case statements I am trying to
turn a Char field into Datetime in for the Order By, however I can not
get it to work. Can someone please take a look and my code below and
tell me what I am doing wrong. Thank you.

ORDER BY
CASE WHEN @SortBy = 'dttm_stamp' THEN dttm_stamp End,
CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(char(10),
Event_Date1,101) as datetime) End,
CASE WHEN @SortBy = 'FullName' THEN Emp_lastname + ', ' +
Emp_firstname End,
CASE WHEN @SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
Emp_firstname End DESC,
CASE WHEN @SortBy = 'Emp_SSN' THEN Emp_SSN End

View 11 Replies


ADVERTISEMENT

Error When Convert Or Cast Functions From Varchar To XML Datatype

Dec 29, 2007

Hi I have a varchar(8000) and currently XML files are stored in varchar(8000).Some times when i am doing manuplactions in my varchar column i am getting with special characters error. so now i want to keep my column varchar(MAX) and when i am doing calculations i will convert my varchar datatype to xml datatype. By doing this i hope there wont be any special character problems.
When i am doing calculations with the wellformed xml i am getting error for both convert and cast methods as below 
I am trying to do convert(xml,MyVarcharColumn)
Implicit conversion from data type xml to nvarchar is not allowed. Use the CONVERT function to run this query.
Also i tried with casting and getting same problme. is there any way to convert
 
please suggest me
 
Thanks
Dilip

View 1 Replies View Related

SIMPLE Command To Convert String To Number? Not CAST Or CONVERT.

Aug 15, 2006

Dear Experts,Ok, I hate to ask such a seemingly dumb question, but I'vealready spent far too much time on this. More that Iwould care to admit.In Sql server, how do I simply change a character into a number??????In Oracle, it is:select to_number(20.55)from dualTO_NUMBER(20.55)----------------20.55And we are on with our lives.In sql server, using the Northwinds database:SELECTr.regionid,STR(r.regionid,7,2) as a_string,CONVERT(numeric, STR(r.regionid,7,2)) as a_number,cast ( STR(r.regionid) as int ) as cast_to_numberFROM REGION R1 1.00112 2.00223 3.00334 4.0044SELECTr.regionid,STR(r.regionid,7,2) as a_string,CONVERT(numeric, STR(r.regionid,7,2) ) as a_number,cast (STR(r.regionid,7,2) as numeric ) as cast_to_numberFROM REGION R1 1.00112 2.00223 3.00334 4.0044Str converts from number to string in one motion.Isn't there a simple function in Sql Server to convertfrom string to number?What is the secret?Thanks

View 4 Replies View Related

Error Using Case Expression In Order By Statement

Feb 22, 2008

I have been trying to get the following Selects to work using a case expression in the order by section.

I know I can easily separate out the two statements but I want to do a select using the case statement below ;
however, I keep getting error 16 --"Order by items must appear in the select list if the statement contains a union.

If remove the case statement and put order by "internalID desc" I receive no errors. Moreover, when I take out the union statement and execute the two select statements with each including the case expression it runs as planned.

Can anyone tell what the problem is here? I have combed the web looking for an answer, but it seems that the statement is valid.


Thanks
J
declare @date
set @date = '2001'



select internalID from section_data_v3

union

select internalID from section_data_v4

order by
case when (@date = '2001') then internalID end desc

View 5 Replies View Related

CASE Statement Error: Cannot Convert A Char Value To Money

Nov 6, 2007

I am trying to write a Procedure in SQL 2005 that retreives a list of rows from the database. I pass to the procedure sorting parameters. This procedure works fine for all of the fields that I enter in the Order By, except for one.
The field that does not work is a varchar(500) field (named Description).
I am not sure what the problem is.
The error that I am getting is:

Msg 235, Level 16, State 0, Line 13

Cannot convert a char value to money. The char value has incorrect syntax.

Attached is the T-SQL Code. The declare and set statements in the beginning are for informational purposes.
Any help is appreciated.
------------------------------------------------------------------------------------------------------
declare @Match varchar(75)

declare @NumRows int

declare @StartPos int

declare @OrderBy varchar(25)

declare @OrderDir varchar(4)


set @Match = 'dog% AND bark%'

set @NumRows = 25

set @StartPos = 100

set @OrderBy = 'Description'

set @OrderDir = 'ASC'


WITH catitems AS

(

SELECT ci.ID, ci.SupplierCode, ci.Description, ci.AUDIO_LINK, ci.SoundLength, ci.HighCost, ci.Channels,

ROW_NUMBER() OVER (ORDER BY

CASE

WHEN @OrderBy='ID' AND @OrderDir='ASC'

THEN CAST(ci.ID AS int)

WHEN @OrderBy='SupplierCode' AND @OrderDir='ASC'

THEN CAST(ci.SupplierCode As int)

WHEN @OrderBy='Description' AND @OrderDir='ASC'

THEN CAST(ci.[Description] As varchar(500))

WHEN @OrderBy='HighCost' AND @OrderDir='ASC'

THEN CAST(ci.HighCost AS money)

WHEN @OrderBy='Channels' AND @OrderDir='ASC'

THEN CAST(ci.Channels AS smallint)

END ASC,

CASE

WHEN @OrderBy='ID' AND @OrderDir='DESC'

THEN CAST(ci.ID AS int)

WHEN @OrderBy='SupplierCode' AND @OrderDir='DESC'

THEN CAST(ci.SupplierCode As int)

WHEN @OrderBy='Description' AND @OrderDir='DESC'

THEN CAST(ci.[Description] As varchar(500))

WHEN @OrderBy='HighCost' AND @OrderDir='DESC'

THEN CAST(ci.HighCost AS money)

WHEN @OrderBy='Channels' AND @OrderDir='DESC'

THEN CAST(ci.Channels AS smallint)

END DESC) As RowNo

FROM TableName As ci

WHERE CONTAINS (ci.Keywords, @Match) AND ShowOnWeb=1

)

SELECT catitems.ID,

catitems.SupplierCode,

catitems.Description,

catitems.AUDIO_LINK,

catitems.HighCost,

catitems.Channels

FROM catitems

WHERE RowNo BETWEEN @StartPos AND @StartPos + @NumRows -1
------------------------------------------------------------------------------------------------------


Thanks,

Aric


View 1 Replies View Related

Case Statement Using Cast

Jan 28, 2007

Hi guys,

The value in the field ACCOUNTS.ACCOUNTKEY is something like: '3130005'

I need to read the characters from position 4 to 6. If the value of that Substring is equal to the VALUE Zero then write "Zero".

In the code below, the first "case" is working nice, but the second (red one) is getting ERROR.

Please Help.

"SELECT ACCOUNTS.ACCOUNTKEY," _
& " Case When SUBSTRING(ACCOUNTS.ACCOUNTKEY, 4, 3)= '000' then 'Zero'" _
& " Case When CAST(SUBSTRING(ACCOUNTS.ACCOUNTKEY, 4, 3) as int) =0 then 'Zero'" _
& " Else 'Unknown'" _
& " End " _
& "AS 'Finding Zero' "
Thanks in advance,

Aldo.

View 4 Replies View Related

ORDER BY CAST(classname As Int)

Jul 24, 2001

When I do the following:

SELECT Name, Age FROM Students ORDER BY CAST(classname as int)

I'll get an error saying that "can't convert '1b' to int" and I am completely ok with that. However, I would still like to ORDER BY the int
value in the column [classname] that is of type varchar(5) so that i would get the ordering numeric. I don't want '22b' to come before '3b' !

Thanks for any help !

View 4 Replies View Related

Cast Or Convert

Feb 18, 2008

 Hi,I want to turn int to double/decimal  in microsoft sqlSHould i use cast or convert?if so, how i do it thanks, 

View 1 Replies View Related

CAST/Convert

Mar 15, 2006

I need Query syntax to cast/convert values as follws.

Val.: 00005000010260002180 - Result must be: 5.1.2600.2180
Val.: 00005000000213400001 - Reslut must be : 5.0.2134.1

Dots must also be contained in result

View 2 Replies View Related

CAST Or Convert

Oct 8, 2014

Have the following in my SELECT statement, which I'm having issues with when I modify it to include a CAST or a CONVERT.

CONCAT(PER.[PERSON-REF],ROW_NUMBER() OVER (PARTITION BY PER.[PERSON-REF] ORDER BY TEN.[tenancy-ref])) AS 'ID'How do I convert or cast it to a varchar (20)?

View 8 Replies View Related

Convert AND Cast

Nov 6, 2007

We have a 3rd party application that connects to our SQL 2005 as a external database source.

Our external database has a 'datein' field that for some reason is stored as a varchar(50).

I can use cast to convert the field to datetime, but how would I then format to the yyyy-mm-dd format in the same select statement(using in view)?

I need to convert this field to a format of YYYY-MM-DD in order for the 3rd party application to search on it correctly.
Below is an example of the data --
FieldName = DateIn
DateType = Varchar(50)
2006-07-06
Sep 12 2007 11:16AM
2007-07-19
Oct 2 2007 12:24PM
2007-08-19
Oct 31 2007 8:00PM
Sep 15 2007 9:25AM
2007-08-18
Oct 16 2007 7:01PM
Oct 30 2007 11:15AM
Aug 29 2007 8:54AM
Aug 29 2007 8:38PM
Aug 25 2007 2:33PM

View 3 Replies View Related

Difference Between Cast And Convert In SQL

Apr 20, 2007

Can anyone explain in simple terms the difference between cast and convert in SQL?

View 2 Replies View Related

Cast/Convert Value To VB Variable

Oct 24, 2005

Hi all,
I have a VB 6.0 application that interacts with an MS Access backend. I am in the process of converting it so that it interacts with SQL Server 2000. The current applications uses Cint, CStr, etc. functions which are MS-Access specific, so I am now switching over to Convert (or Cast) function. The problem is that there are certain places wherein I first need to store the value of the resultant CAST/Convert function in a variable and then use that value in a SQL statement. However, I cant seem to figure out a way of storing the results from CAST/CONVERT functions in the VB 6.0 variable. All the examples on Internet show use of these functions directly in an SQL statement e.g. "Select CAST(title as Int) from xyz", etc.
Can anybody tell me how can i get the values to be stored in the variable? I am really stuck here and cant seem to progress.

Thanks in advance for all your help.

Regards:
Prathmesh

View 2 Replies View Related

Update With Different CAST And CONVERT

Jul 6, 2014

I have a table with all varchar data for all different fields for money and int etc. I want to do a calcuation in one field with the rule as below:

UPDATE [dbo].[tblPayments]
SET [PreInjuryWage]=
CASE
WHEN [WeekNo]<14
THEN ([MaxWorkCover]+ [WeeklyEarnings] )/0.95
ELSE ([MaxWorkCover] + 0.80 * [WeeklyEarnings] ) /0.80
END

I tried this command after many other ways of tries

UPDATE [dbo].[tblPayments1]
SET [PreInjuryWage]=
CASE
WHEN [WeekNo]<14
THEN CAST ( (cast([MaxWorkCover] as money )+ cast([WeeklyEarnings] as money ))/0.95 AS Varchar(10) )
ELSE CAST ( (convert(money, [MaxWorkCover] + (0.80 * convert(money, [WeeklyEarnings] )) )/0.80 ) as varchar(10))
END

The structure of the table ( its a legacy table from 2000 i beleive)

CREATE TABLE [dbo].[tblPayments](
[PaymentID] [int] IDENTITY(1,1) NOT NULL,
[ClaimID] [int] NOT NULL,
[WeekNo] [smallint] NULL,

[code]....

Arithmetic overflow error converting numeric to data type varchar.

View 6 Replies View Related

The Difference Between Cast And Convert

May 14, 2008

Can anyone tell me what is the difference between Cast and Convert...?

BOL tells me that they provide similar functionality; it doesn't say that they provide the same functionality.


What is the purpose of having both... is the reason historical?

Which one performs better?

View 3 Replies View Related

Cast Or Convert -2 To Just Show 2

Mar 24, 2008

ToMatch=58
ToNoMatch=1


select @Agg1= Cast(cast(cast(cast(Max(TotMatch) as decimal) / cast((Max(TotNoMatch) + Max(TotMatch)) as decimal)* 100 as int) - 100 as int) as varchar) + '%' FROM #Rpt;

if i try this it is giving me answer in -2%
how i can remove the - sign



also if I try the same statement in different way. well I am going to post in other post.

View 3 Replies View Related

Correctly ORDER BY Date That Has Been Cast As A Varchar

May 23, 2008

how do you get it to sort correctly for the date? at the minute its sorting on the characters rather than actual date value





Code Snippet
INSERT INTO @TempItems (OrderID)
SELECT OrderID
FROM Orders o
INNER JOIN Customers c ON c.CustomerID = o.CustomerID
INNER JOIN Employees e ON e.EmployeeID = o.EmployeeID
ORDER BY
CASE @SortOrder --Order ASC
WHEN 0 THEN cast(OrderID as varchar(100))
WHEN 1 THEN cast(c.CompanyName as varchar(100))
WHEN 2 THEN cast(e.FirstName as varchar(100))
WHEN 3 THEN cast(o.OrderDate as varchar(100))
WHEN 4 THEN cast(o.RequiredDate as varchar(100))
WHEN 5 THEN cast(o.ShippedDate as varchar(100))
ELSE '1'
END,

View 4 Replies View Related

What Is Diff Betn Cast And Convert

May 22, 2008

 Hi alll,can anyone tell me that In which cases cast is used in db and what is diff betn cast and convert

View 9 Replies View Related

Cast Or Convert And Aggreate Function

Dec 1, 2000

Hi people,
I am trying to use Aggregate function like count or average on a column which has a datatype Varchar. In order to use avg or count on it , I am doing a cast on it.
If somebody has use Cast/Convert with aggregate function please help me
Thanks
Jesal

View 2 Replies View Related

CAST Or CONVERT When Calculating AVG From INTs?

Nov 13, 2013

I have an INT field that I want to take the average value of, to the 2nd decimal. Is there a difference between using CAST vs CONVERT?

CAST

Code:
CAST(Avg(CAST(units AS DECIMAL(10,2))) AS DECIMAL(10,2))
from myTable
CONVERT

Code:
CONVERT(numeric(10,2),avg(CONVERT(numeric(10,2),units)))
from myTable

View 4 Replies View Related

Cast Convert(varchar(12),newDate, 101)

Mar 25, 2008

1)Cast(isnull(Partl,0) as smallint)
2) convert(varchar(12),newDate, 101)

what two lines would do. ??

thanks,

View 1 Replies View Related

Convert Or Cast HexaDecimal To Bigint

Aug 21, 2006

Hi ,

I have a hexadecimal string value. I want to convert it to Bigint in Sql Server 2005.

The Hexadecimal value is '0x000000000000000F'.

How is it possible to convert into Bigint.

Please help me

Thanks in advance

Srinivas





View 6 Replies View Related

SQL Server 2014 :: CASE Condition Not Affecting CAST Output

Jun 10, 2014

I've a variable in my SP that I'd like to use to change the format of my output. Try this!

select case when 1=2 then cast(1 as decimal(10,2)) else cast(2 as decimal(10,0)) end

Then this:

select case when 1=1 then cast(1 as decimal(10,2)) else cast(2 as decimal(10,0)) end

Why in either case, the output is returned as n.nn ? Whilst single select expressions (like these):

select cast(1 as decimal(10,2)) -- = 1.00
select cast(2 as decimal(10,0)) -- = 2

Work fine.

View 8 Replies View Related

SQL Server 2012 :: Using CAST Or Convert Functions

May 31, 2015

How do I use the CAST or CONVERT function in the code below, I require a third column (named Diff) which Minus the StartTime from the EndTime and the result is outputted in the third column (named Diff).

Calculation: @Diff = (@EndTime - @StartTime)

I still want the variables (@StartTime and @EndTime) to remain as nvarchar.

The code:

DECLARE @StartTime nvarchar(10) = '12:10';
DECLARE @EndTime nvarchar(10) = '12:30';
DECLARE @Diff time(1) = '00:00';
SELECT @StartTime AS '@StartTime', @EndTime AS '@EndTimes', @Diff AS '@Diff';

View 7 Replies View Related

Date Conversion Woes: Cast? Convert?

Nov 7, 2007

I have been having some trouble trying to get the date format YYYYMMDD 00:00:00.00 to convert to MM/DD/YYYY. I am using SQL 2005 and Reporting Services. I attempted several variations to solve this problem as outlined below, with the final working conclusion at the end. I am not saying that this is the BEST or the ONLY way to achieve the solution, but it worked for me.



Code Block
---------------------------------------------------------------------------------------
SELECT DATE_TIME AS DATE1
FROM TRANSLOG
--returns value of 20071027 02:26:24.06
---------------------------------------------------------------------------------------
SELECT CAST(DATE_TIME AS SMALLDATETIME) AS DATE1
FROM TRANSLOG
--returns value of 2007-10-27 02:26:00
---------------------------------------------------------------------------------------
SELECT LEFT(CAST(DATE_TIME AS SMALLDATETIME),11) AS DATE1
FROM TRANSLOG
--returns value of Oct 27 2007
---------------------------------------------------------------------------------------
SELECT CAST(SUBSTRING(DATE_TIME,0,9) AS SMALLDATETIME) AS DATE1
FROM TRANSLOG
--returns value of 2007-10-27 00:00:00
---------------------------------------------------------------------------------------
SELECT CONVERT(VARCHAR(10), DATE_TIME, 103)
FROM TRANSLOG
--although this works with GETDATE(), it does not work with the DATE_TIME field
---------------------------------------------------------------------------------------
SELECT CONVERT(VARCHAR(10), CAST(DATE_TIME AS SMALLDATETIME), 101) AS DATE1
FROM TRANSLOG
--THIS WORKS!!! Displaying 10/27/2007





Hope this helps somebody someday!

-Jody

View 5 Replies View Related

Problem With CAST And CONVERT In SQL Server2000 Converting Decimal Places From 4 To 2

May 11, 2005

All of my currency columns are only storing 2 decimal places when I insert into the database but when I pull out the data with a SELECT statement, I always get 4 decimal places instead of the 2 that were inserted. 
For example: 
Database Price            SELECT statement Price
100.56                           100.5600
I have tried to use the CAST and/or CONVERT commands but I cannot get the output to come out as 100.56.  Has anyone had a similar problem?
Thanks

View 5 Replies View Related

T-SQL (SS2K8) :: Using CAST Or CONVERT To Change Data From String To Datetime?

Apr 16, 2014

i am trying to take a field that has part of a date in it, so I have to parse it out as follows:

SUBSTRING(a1.Field1, 3, 2) + SUBSTRING(a1.Field1,5,2) + '20' + LEFT(a1.Field1,2)

This is because a date of 04/16/2014 will show as 160416 in the first part of the field I need to parse it out of, thus becoming 04162014.

From there I then need to convert this "date" into a legitimate SQL datetime type, so that I can then run a DATEDIFF to compare it to when the record was actually entered, which is a separate field in the table, and already in datetime format.

When I use the below statement, I am getting the message that, "Conversion failed when converting date and/or time from character string."

CAST((SUBSTRING(a1.Field1, 3, 2) + SUBSTRING(a1.Field1,5,2) + '20' + LEFT(a1.Field1,2)) as datetime)

I also tried CONVERT(datetime, (SUBSTRING(a1.Field1, 3, 2) + SUBSTRING(a1.Field1,5,2) + '20' + LEFT(a1.Field1,2)), and got the same message.

how I can parse that field, then convert it to a datetime format for running a DATEDIFF statement?

View 9 Replies View Related

CS0266: Cannot Implicitly Convert Type 'object' To 'bool'. An Explicit Conversion Exists (are You Missing A Cast?)

Apr 20, 2008

Using OnSelected on the SqlDataSource----here is my currect code:private void On_Load(Object sender, SqlDataSourceCommandEventArgs e){if (e.Command.Parameters["@DueDate"].Value = "NULL"){e.Command.Parameters["@DueDate"].Value = "0000-00-00 00:00:00.000";}}
I am trying to change the value from  NULL(in a datetime field) to "0000-00-00 00:00:00.000" for use on the page.Any ideas, suggestions, or thoughts would be greatly appreciated!
,Gary"we truly fail, only when we quit."

View 2 Replies View Related

ORDER BY CASE

Dec 22, 2006

this is my query="SELECT i.itemid,title,SortKey from Items AS i JOIN Links AS L ON(i.ItemID=L.ItemID) WHERE L.instructorID='12232' AND courseID='12' ANDtype='Audio' order by CASE WHEN Sortkey is not null then 1 else 0 end"My SortKey can be NULL. Here's the output I am getting:(the || is to denote sortkey column)37542 Tape 1 ||37544 Tape 2 ||37819 Symphony1 ||37820 Symphony2 ||37821 Symphony3 ||37828 Symphony ||60962 Test ||61570 New Test Record |Africa|61572 Test 3 |Africa 1|63186 Music for Strings |Brazil|I want use Sortkey when it is not null. desired output:61570 New Test Record |Africa|61572 Test 3 |Africa 1|63186 Music for Strings |Brazil|37542 Tape 1 ||37544 Tape 2 ||37819 Symphony1 ||37820 Symphony2 ||37821 Symphony3 ||37828 Symphony ||60962 Test ||

View 10 Replies View Related

2 Case Statements In Order By

Oct 31, 2013

It will be part of the stored proc, but for now I couldn't even get it running in ssms. It will be two parameters/variables, one for order by column name and other for order by direction, i.e. desc or asc.I have tried following three ways, but none is working:

(1)
order by case when @Sort_by= '[A_ID]' AND @Sort_Dir ='Desc' then A_ID end desc
case when @Sort_by= '[A_ID]' AND @Sort_Dir ='Asc' then A_ID end asc

(2)
order by case when @Sort_by= '[A_ID]' AND @Sort_Dir ='Desc' then A_ID desc end
case when @Sort_by= '[A_ID]' AND @Sort_Dir ='Asc' then A_ID asc end

(3)
ORDER BY CASE @Sort_by when '[A_ID]' then [A_ID] end
Case @Sort_Dir when 'Desc' then desc end

View 3 Replies View Related

How To Convert Iif To Case

Dec 10, 2004

Hi ,
I am facing problem for converting MS Access 2000 queries to SQL Server views.Specially in case of Iif statement
given below

IIf(Sum((Hour([out]-[in])+Minute([out]-[in])/60)/(Hour([deptend]-[deptstart])+Minute([deptend]-[deptstart])/60))<1,Round(Sum((Hour([out]-[in])+Minute([out]-[in])/60)/(Hour([deptend]-[deptstart])+Minute([deptend]-[deptstart])/60)),2),1) AS [Normal Attn]

what will be the 'CASE' statement of the above query.
I am waiitng for your kind reply

Best Regards
AKH

View 2 Replies View Related

Alternative To CASE In The Order By Statement?

Feb 15, 2008

 The query below at the bottom works, but when I try to add the line below (a third line/argument in the CASE statement) then I get an error. It is not possible to have a table name and a DESC (sort order) in the same CASE line/argument. Are there other ways to accomplish this, because I would like to sort with both "h.ObjectType" and "h.ObjectType DESC"?             WHEN @SortBy = 2 THEN h.ObjectType DESC      SELECT weight, ObjectText.ObjectId, ObjectText.ObjectType, ObjectText.Title, ObjectText.ShortText    FROM @hits h INNER JOIN ObjectText ON h.id = ObjectText.ObjectId AND h.ObjectType = ObjectText.ObjectType    WHERE ObjectText.LanguageCode = @LanguageCode    ORDER BY        CASE WHEN @SortBy = 0 THEN weight             WHEN @SortBy = 1 THEN h.ObjectType        END    DESCRegards, Sigurd 

View 4 Replies View Related

ORDER BY, CASE, With Multiple Columns

Nov 7, 2003

I'm unable to specify multiple columns in my order by statement if i use a case statement.
Does anyone know why this is, or what syntax would make this work?

Thanks


SELECT ....
ORDER BY (CASE Lower(@SortExpression)
WHEN 'prodname' THEN prodname, prodprice
WHEN 'prodsize' THEN prodsize, prodname
WHEN 'prodprice' THEN prodprice, prodname
Else prodcompany, prodname
END)

View 5 Replies View Related







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