Sort a varchar field numerically
select streetnum from address_points_sp where streetname='THORNWAY' and suffix='AVE' order by streetnum asc
is the sql I'm trying to run. But StreetNum is defined as a varchar... unfortunately. I cannot change the DB schema. Is there a way to do this via sql?
Also, I need to find out the lowest number and the highest....
Thank you
If you are quite sure that you'll only have Numeric data in streetnum field, try TO_NUMBER function.
SQL> desc temp_1
Name Null? Type
COL_1 VARCHAR2(3)
SQL>
SQL> insert into temp_1 values ('3')
2 /
1 row created.
SQL> commit
2 /
Commit complete.
SQL> ed
Wrote file afiedt.buf
1 select to_number(col_1)+1 from temp_1
2* where col_1 = '3'
SQL> /
TO_NUMBER(COL_1)+1
4But there is also a potential problem if you have non-numeric data in the field. Like below:
SQL> select to_number(col_1) from temp_1
2 /
select to_number(col_1) from temp_1
ERROR at line 1:
ORA-01722: invalid numberCheers
Sarma.
Similar Messages
-
In one of my tables I have a fields called : f1_code which is varchar(20). This field got numbers as well as characters. I need to soft the contents using this field.
Ex: If I have the following values in this field :
3s
100a
20b
1
7t
When I sort by this field, my output should be in the following order
1
3s
7t
20b
100a
Is it possible to do this in sql query? If so please advice. Any help is greatly appreciated. I tried many queries, but could not find the solution.SQL> with virtual_table as
2 (select '3s' col1
3 from dual
4 Union All
5 select '100a'
6 from dual
7 Union All
8 select '20b'
9 from dual
10 Union All
11 select '1'
12 from dual
13 Union All
14 select '7t'
15 from dual)
16 select vt.col1
17 from virtual_table vt
18 order by to_number(translate(vt.col1,translate(vt.col1,'1234567890',' '),' '));
COL1
1
3s
7t
20b
100a
SQL> -
How can we sort up currency field in alv grid??
Hi GUrus,
Can any one suggest me how to sort the currency field in alv grid...Please help me out of this issue..
Thanks in advance!!!
regards,
Kranthi.hii,
SAP provides a set of ALV (ABAP List Viewer) & function modules, which can be used to enhance the readability and functionality of any report output.
ALV is a flexible tool used for displaying lists.The tool provides common list functions & can be enhanced by self-defined options.
so u will get the option for sorting in your alv report.
Thanks -
Im getting an error when running a procedure that includes this code.
I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
DECLARE @retval AS DECIMAL(12,2)
DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
DECLARE @sqlcmd AS NVARCHAR(150)
DECLARE @paramdef NVARCHAR(150)
SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
--default
SET @retval = 0.0;
EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
SELECT @retval
DECLARE @return_value DECIMAL(12,2)
EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
@SpreadKey = 1,
@MonthNumber = 4
SELECT 'Return Value' = @return_value
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for:
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
>> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
the shoe size, the phone number or something else at run time of this entity.
In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point.
Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity.
Do you know that SQL is a declarative language? This family of languages does not use local variables!
Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.
Think about how silly this is:
SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental.
We need to see the DDL so we can re-write this mess. Want to fix it or not?
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Is it possible to sort by multiple fields?
Is it possible to sort the music library by multiple fields in a prioritised order? For example, I would like to sort by the following columns, in the following order:
Album Artist
Album
Track Number
for some reason I can't seem to do this, sorting by Album artist alone is not working for me, as some CD's I've imported have featured artists and this breaksup the listing order.
ThanksThanks Thomas
Unfortunately, this solution did not work for me, cover flow still shows multiple instances of the same artwork for various groups of tracks from the same album.
The thing I don't understand is why sorting by the "sort album artist" field does not group all the tracks from an album together.
My specific example (I still can't get a screenshot posted):
I have two Gwen Stefani albums, both ripped from CD (not imported from the itunes store). both albums have a majority of track where Gwen is the only artist and two or three track with featured artists. I have filled the "album artist" and "sort album artist" tags to all read Gwen Stefani, however, if I sort by either of these columns (in cover flow mode), what I get is this:
all the tracks from one ablum where Gwen Stefani is the artist
then all the tracks from the other album where Gwen Stefani is the artist
then (in alphabetical order by featured artist) the remaining tracks from both albums - ie, the albums are mixed up
for each group of track I see an cover flow art work.
I should say that I have turned off the compilation tag on all of my albums because this ends up saving the file in a compilation folder, not in the artist folder on my hard drive - but it doesn't make a difference either way to the way I see the files sorted in itunes.
It's really frustrating! -
Best practice to define length for varchar field of table in sql server
What is best practice to define length for a varchar field in table
where field suppose Remarks By Person varchar(max) or varchar(4000)
Could it affect on optimization in future????
experts Reply Must ...
Dilip Patil..Hi Dilip,
Varchar(n/max) is a variable-length, non-unicode character data. N defines the string length and can be a value from 1 through 8,000. Max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered
+ 2 bytes. We always use varchar when the sizes of the column data entries vary considerably. While if the filed data size might exceed 8,000 bytes in some way, we should use varchar(max).
So the conclusion is just like Uri said, use varchar(max) or varchar(4000) is depends on how much characters we are going to store.
The following document about varchar in SQL Server is for your reference:
http://technet.microsoft.com/en-us/library/ms176089.aspx
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
Is there a way to sort a PDF file with multiple pages by a specific field within the PDF? All pages have the same invoice format and i would like to sort by a field within and then print the documents. (Vendor, PO#, Date, ect.)
When you say field, do you mean specifically a form field, such as a text field? Or is the information regular text on the page?
-
Collections.sort() - sort on multiple fields?
I have a collection of objects in a List that I need to be able to sort on each field individually. For example, the data in the List is eventually displayed on a table in a web page. The user is able to click on a column header and the table is to be refreshed with the list contents sorted by that column (asc/desc).
I would rather not re-query the DB for this list (it's pretty static and already saved in memory). So if I use the Collections.sort(myList, new Comparator() { ...} ) method, is it possible for me to pass the field/direction of the sort into the Comparator? Or, do I have to define individual Comparators for every field that the user can sort by and surround it all by an ugly switch statement?Honestly I think that a re-query to the DB is the best approach. Remember that any decent DB engine will cache queries so it will really only have to re-perform the sort algorithm.
Commercial databases are very fast and almost never the source of a performance bottleneck.
I realize this isn't the answer you want, but in my experience it is the best solution, if you really can't stand to re-query then as mentioned creating your own comparator is the way to go. -
I have a procedure which accepts a varchar field as input and compares it with each value in a table. how do I code it.
e.g. proc1(xx IN varchar, yy OUT)
--say column name is abc then
where abc = xx;
Dosent giving any output.here it goes
SQL> ED
Wrote file afiedt.buf
1 CREATE OR REPLACE PROCEDURE
2 COMPARE_VARCHAR_FIELDS(XX IN VARCHAR,YY OUT VARCHAR)
3 IS
4 A NUMBER:=0;
5 BEGIN
6 FOR I IN (SELECT * FROM AX WHERE X=XX)
7 LOOP
8 A:=A+1;
9 END LOOP;
10 IF A>0 THEN
11 YY:=XX||' FOUND '||A||' TIMES';
12 ELSE
13 YY:=XX||' NOT FOUND';
14 END IF;
15* END;
SQL> /
PL/SQL procedure successfully completed.
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 Z VARCHAR2(40);
3 BEGIN
4 COMPARE_VARCHAR_FIELDS('x',z);
5 dbms_output.put_line(z);
6* end ;
SQL> /
PL/SQL procedure successfully completed.
SQL> set serveroutput on
SQL> /
x FOUND 3 TIMES
PL/SQL procedure successfully completed. -
It's been a day of learning. I found out that when Kodo gets a
columnlength of -1 for a String field, it will ask the Dictionary for
the sql for generating a Clob. Also when Kodo finds a positive
columnlength it will call getLenString on the dictionary.
We're using MySQL and in this case, when the column-length of a String
is set to -1 this creates a TEXT field and when the column-length is
positive this creates a VARCHAR(column-length) field.
When querying the database, Kodo once again turns to the meta data. When
the column-length has been set to -1 Kodo does a separate query for each
text field. If the column-length is positive, Kodo includes the field in
it's default-fetch-group.
Am I correct so far?
The problem I have is that when a query for a certain field is
performed, I want it to be in the first group fetched. It is always
needed and not that large at all. It will at most be 1500 characters. In
SQL Server and possibly others, I can put the column-length at 1500 and
wind up with a varchar field of 1500 characters long. MySQL however,
does not support anything over 255 characters for a varchar field.
So, I need to create a field of type TEXT to allow it to contain more
than 255 chars. However, I do not want a separate query for the field
since it won't be that big anyway.
I've been able to get this working using the column-length -1 at schema
time and the value 1500 at runtime. This is not at all convenient and
will very likely result in a wrong schema being created or the wrong
query being run in the long run.
Is the solution I just mentioned the only one, or are there other scenarios?
Thanks in advance,
Martin van DijkenMartin-
Your analysis is exactly right. Kodo 3.0 allows a lot more latitude in
how this behavior is defined.
One way in which you might be able to get around this problem is to
leave the "column-length" attribute to -1, but manually force the
mapping to not be the ClobMapping (which is the mechanism by which Kodo
knows to issue a separate query for the object). You can do this by
setting the "custom-mapping" field-level metadata extension to
"com.solarmetric.kodo.impl.jdbc.ormapping.ValueMapping".
I'll be interested to know if this works for you.
In article <[email protected]>, Martin van Dijken wrote:
It's been a day of learning. I found out that when Kodo gets a
columnlength of -1 for a String field, it will ask the Dictionary for
the sql for generating a Clob. Also when Kodo finds a positive
columnlength it will call getLenString on the dictionary.
We're using MySQL and in this case, when the column-length of a String
is set to -1 this creates a TEXT field and when the column-length is
positive this creates a VARCHAR(column-length) field.
When querying the database, Kodo once again turns to the meta data. When
the column-length has been set to -1 Kodo does a separate query for each
text field. If the column-length is positive, Kodo includes the field in
it's default-fetch-group.
Am I correct so far?
The problem I have is that when a query for a certain field is
performed, I want it to be in the first group fetched. It is always
needed and not that large at all. It will at most be 1500 characters. In
SQL Server and possibly others, I can put the column-length at 1500 and
wind up with a varchar field of 1500 characters long. MySQL however,
does not support anything over 255 characters for a varchar field.
So, I need to create a field of type TEXT to allow it to contain more
than 255 chars. However, I do not want a separate query for the field
since it won't be that big anyway.
I've been able to get this working using the column-length -1 at schema
time and the value 1500 at runtime. This is not at all convenient and
will very likely result in a wrong schema being created or the wrong
query being run in the long run.
Is the solution I just mentioned the only one, or are there other scenarios?
Thanks in advance,
Martin van Dijken
Marc Prud'hommeaux [email protected]
SolarMetric Inc. http://www.solarmetric.com -
What is needed for sorting on two fields in a table control
Hi Everybody
I am going to certification in a couple of days. I need some help and was hopeing that you guys could help.
What is needed for sorting on two fields in a table control?
One sorted table and two processing blocks
Two standard tables and one processing blocks
Two standard tables and two processing
Which one is corret??
//ScriptHi Kimallan
I am not sure what is meant by a "processing block". However, it seems the question wants the original table order to be preserved. If so; as far as I understood the problem we need:
itab_proxy[] = itab_main[] .
"two standard tables"
SORT itab_proxy BY field1 field2 .
If we have a sorted table, then it is always sorted by its keys. So, the question seems to become obsolete for that option.
Hope I've understood correct...
Regards
*--Serdar
[email protected] -
Dividing sum of varchar fields?
I'm using SQL Server 2014 and I have the following table containing two varchar fields I need to sum and divide:
CREATE TABLE.[VMs](
[VMID] [int] IDENTITY(1,1) NOT NULL,
[vCenter] [varchar](100) NULL,
[VMName] [varchar](100) NULL,
[Template] [varchar](100) NULL,
[PowerState] [varchar](100) NULL,
[ClusterName] [varchar](100) NULL,
[Disk] [int] NULL,
[DiskPartition] [varchar](70) NULL,
[DiskSizeGB] [decimal](10, 3) NULL,
[Hostname] [varchar](100) NULL,
CONSTRAINT [PK_VMs] PRIMARY KEY CLUSTERED
[VMID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I'm trying to get the distinct sum of 'VMName' and 'Hostname' to get the count of each, and then divide the 'VMName' count by 'Hostname' count on a per 'vCenter' basis.
I'm not sure how to perform calculations against the varchar fields and any help would be appreciated.
Thanks in advance
AdamThis is the main query, the top portion was sample data I just put based on your provided data
;With CTE
AS
SELECT
vCenter
,COUNT(DISTINCT VMName) As CountVMName
,COUNT(DISTINCT HostName) As CountHostName
FROM
@myTable
GROUP BY
vCenter
SELECT *, (CASE WHEN CountHostName <> 0 THEN CountVMName / CountHostName ELSE 0 END) As CountPerVCenter
FROM
CTE
Best Wishes, Arbi; Please vote if you find this posting was helpful or Mark it as answered. -
Sorting a varchar2 field in Report 10g
Dear all,
i have a table of salaries, which have a field RANK_NO VARACHAR2.
I create a report and order it by RANK_NO. but it is not ordering what i want to be. it is ordered like
1
10
11
2
3
4
5
6
7
8
9
then i use the order by cluase like this,
ORDER BY TO_NUMBER(REGEXP_SUBSTR(RANK_NO,'[0-9]+')),
REGEXP_SUBSTR(UPPER(RANK_NO),'[A-Z]+').
but the result is same .
how to sort a varchar2 field in reports?
Thanks & RegardsHi Muhammad,
Use the following Order By clause hope it helps you,
ORDER BY TO_NUMBER (REPLACE (RANK_NO, LTRIM (RANK_NO, '0123456789'))), RANK_NO
Best Regards
Arif Khadas -
Converting varchar field to date
I got a varchar field in DB with format YYYY/MM/DD HH:MI:SS in DB . I want to convert this to date field in RPD. When I did
CAST ( VarChar field AS DATE) in RPD it is not working I am getting sql error.
Thanks for your help.Hi,
can you try once to cast your char as a timestamp.
Hope that works.
Kr,
A -
Automatically trim a varchar field in an update SQL
We have an ETL application that does an update with a varchar field. When the field contains spaces, we see that with an update these spaces are trimmed automatically. We wonder whether there is a HANA setting that can be set to disable this trim....
For your ETL, Is HANA the source system?
If yes, then you got to change at ETL side right?
Regards,
Krishna Tangudu
Maybe you are looking for
-
AirPort allows one user at a time
When I am connected with one device, my iPhone, for example, all other devices (AppleTV for instance) can connect to the base station, however they cannot connect to the internet, unable to successfully lg into the base station. Something like that.
-
Adobe Audition, Audigy 2 ZS Platinum, can no longer hear guitar :-\
I've recently reformatted my computer, installed the Audigy 2 software, and installed Adobe Audition. Using Line In 2 on the front of my pc, I was able to plug in a guitar, and hear the guitar via headphones. I can use the remote's record button to i
-
Captivate 6 Copy and Paste issue
After copying a Text Entry Box, Captivate 6 persist in pasting the same Text Entry Box object after several other objects (i.e. screenshots) have been copied to the clipboard. OS is Windows 7.
-
I am trying to install LR & PS on my iMac already have on my laptop, but when using the creative cloud app i just get a spinning wheel of death?? everything else in the creative cloud desktop app working / loading just the bit that i need not working
-
Mysql.sock - connection error (code 2002)
Performed a clean install of SL Server. Enabled Web and MySQL services. When using GUI (SequelPro of MySQL GUI Tools) I get a mysql.sock connection error. "Could not connect to MySQL instance at localhost. Error: Can't connect to local MySQL server t