CharIndex, Left T-SQL Question

Feb 15, 2008

Hello,

I was hoping someone could help me with this SQL statement.

The column 'options.optionDescrip' is a varchar field.

Some values of the 'options.optionDescrip' contain commas, some do
not.

We are trying to evaluate against any data in the
'options.optionDescrip' column located to the left of a comma (if a
comma does exist, which it may not). If no comma exists, then we try
and evaluate against the entire field, not just the part to the left
of the comma.

SELECT options_optionsGroups.idProduct FROM options_optionsGroups
JOIN Options ON options_optionsGroups.idOption=options.idOption
JOIN products ON options_optionsGroups.idProduct=products.idProduct
WHERE (CASE WHEN CharIndex(',',options.optionDescrip) = 0 THEN
options.optionDescrip LIKE '" & gauge & "%' ELSE
Left(options.optionDescrip,CharIndex(',',options.o ptionDescrip)) LIKE
'" & gauge & "%' END)

Thanks for any input you can provide, I appreciate it.

View 1 Replies


ADVERTISEMENT

SQL Server 2008 :: Left Function And CHARINDEX

Mar 30, 2015

SELECT LEFT(InstanceName,CHARINDEX(' ',InstanceName)-1)
FROM ServerDB

Returns the following error.

Invalid length parameter passed to the SUBSTRING function.

View 2 Replies View Related

How To Return Partial String Using CharIndex And Left In Same Select

Jun 22, 2015

Select
left(
[Description],(charindex(';',[Description],1)-1))
from xxxx

Example of Description contains

Ankle Supports; Color=Black; Size=S

So I want the left side up to and NOT including the semi colon.

View 14 Replies View Related

Alternative For LEFT() And CHARINDEX() That Works With Text Data Type

Jun 26, 2007

I have a stored procedure that receives a list of ids, to get the emails of each of those ids. The problem that I'm having is that I'm using a char data type that is max length is 8000, but the contact lists are getting bigger and soon they might reach the variable max length. The contact list that I receive will look something like this "1234,67523,67875,789687,", I'm using "," as a separator. Right now what I do is this
@array_value = LEFT(@ContactList, @separator_position - 1)
 
The LEFT function doesn't work with data types text and ntext. But I'm in need of a string data type with a max length bigger than 8000. So I will apreciate if anyone knows of another function that does the same or similar and works with text data type, or any other ideas will be welcome.
 
Thanks,
 Erick

View 8 Replies View Related

SQL Server 2008 :: Using Left And Charindex To Parse String / Getting Rid Of Rest Of Data

Jun 16, 2015

I am trying to erase some erroneous bad data in my table. The description column has a lot of </div>oqwiroiweuru</a> weird data attached to it, i want to keep the data to the left of where the </div> erroneous data begins

update MyTable
set Description = LEFT(Description(CHARINDEX('<',Description)-1)) where myid = 1

that totally works.

update MyTable
set Description = LEFT(Description(CHARINDEX('<',Description)-1)) where myid >= 2

gives me a Invalid length parameter passed to the LEFT or SUBSTRING function. The statement has been terminated error.

View 2 Replies View Related

Transact SQL :: Left Pad With 0 And Extract 2 Characters On The Left?

Oct 28, 2015

I have a table PLACE with a character column CODE

[Code] [nchar](4) NULL

I need to left pad the column with 0 if it is less than 4 characters long and extract the first 2 characters on the left into a new column COUNTY_CODE.

How can I do that in transact SQL?

I tried:
     
SELECT  RIGHT(RTRIM('0000'+ISNULL([Code],'')),4)     
   FROM [Place]
   WHERE [Place Code]='B' and [Code]='627'

And I got 0627. And how do I extract the first 2 characters?

View 10 Replies View Related

Remove Space Left To Right And Right To Left

Oct 24, 2013

How to remove space left to right and right to left

If I give limit >60 for first 60 character; limit 60< second 60 character

Result would be check if space at 60 character if yes remove and go the 59 character check then space remove and 58 character check if there is charater then display

As well as after 60 character to till 120 for right space

View 5 Replies View Related

Left Join Vs Left Outer Join Syntax Generates Different Execution Plans

Apr 16, 2008



Anyone know why using

SELECT *
FROM a LEFT OUTER JOIN b
ON a.id = b.id
instead of

SELECT *
FROM a LEFT JOIN b
ON a.id = b.id

generates a different execution plan?

My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".

Any enlightenment is very appreciated.

Thanks

View 5 Replies View Related

CHARINDEX

Jul 23, 2005

SQL Server 2000Ya know, it is always the simplest stuff that gets ya !!I am having the hardest time getting a simple piece of code working.Must be brain dead today.Goal: Get the users full name from a stringHere is sample data:"LDAP://blahblahblah/CN=Kevin Jones,OU=DevEng,DC=nobody,DC=priv,DC=com"Code:IF LEN(@strReturnValue) > 0 BEGINSELECT @strReturnValue = SUBSTRING(@strReturnValue,(CHARINDEX('CN=',@strReturnValue)+3),(CHARINDEX(',',@strReturnValue)-1))ENDIt will extract:"Kevin Jones,OU=DevEng,DC=nobody,DC=priv,DC=com"I want it to extract:Kevin JonesThanks.

View 3 Replies View Related

Using CHARINDEX Vs LIKE In WHERE?

Jul 20, 2005

Hi All,Just wondering if it's any more efficient to use the following SQLstatement to return a partial match from a column as opposed to thesecond statement.SELECT * FROM Table1 WHERE CHARINDEX('value', mycol) > 0Versus:SELECT * FROM Table1 WHERE mycol LIKE '%value%'Does anyone have any thoughts on whether or not either of thesestatements would return a result quicker than the other?Many thanks in advance!Much warmth,Murray

View 5 Replies View Related

Substring, Charindex, ??

Feb 18, 2000

I am looking for a way to return only the numbers from the following example:

Column1 varchar(255)

Column1
---------------------
10 rows copied.
55004 rows copied.
1000004 rows copied.

Once I get the numbers I will then convert (Cast) them as Int.

Thank you in advance,
tw

View 1 Replies View Related

Charindex And Substring

May 26, 2005

Hi All,

I have an address field that has data that needs to parsed. The data has different formats. I have tried charindex and substring but I am not getting the results I need.

Here is what the data looks like:

Paper Mill Rd 3332
Allegheny Ave 13 1/2
Balto Nat'l Pike 6600 R-2
Rolling Rd N 3030


Here is the results I am looking for:

street dir street number street name street type street unit
3332 Paper Mill Rd
13 1/2 Allegheny Ave
6600 Balto Nat'l Pike R-2
N 3030 Rolling Rd

Can you help? Thanks.

View 5 Replies View Related

IN Clause And CharIndex

Jan 20, 2004

Hi, The following stored procedure creates this error, "Syntax error converting the varchar value '17,18,405,408,406,493' to a column of data type int." I tried using a Convert and a Cast function but it still failed. I then read something about using the CharIndex function, but I can't figure it out. Any help would be much appreciated in getting this to work.
Thanks

CREATE PROCEDURE [ResourceProducts]
@ProductHtml varchar(200)
AS

SELECT Resources.ResourceId, Resources.Heading
FROM Resources
INNER JOIN Products
ON Resources.ResourceId IN (Products.Resources)
Where Products.ProductHtml = @ProductHtml
GROUP BY Resources.Heading, Resources.ResourceId
GO

View 5 Replies View Related

How To Use IF Or Case With Charindex?

Dec 18, 2007

Hi
I have a column col1 in a table having below strings. How do I get only the required part of the string as I explaind below. (Needed strings are followed by i.e as below).


txtString=duracell+alkaline+battery+&submit1=Search&OVR31&OVKWID=24137211531
i.e : duracell+alkaline+battery+

txtString=sealed+lead+acid+batteries+&submit&gclid=CMekn-fesZAodpzIcHA
i.e : sealed+lead+acid+batteries+

ID=3&Department=
i.e : 3

ID=22893
i.e : 22893

lngSessionId=837541253&pid=22714
i.e : 22714

CCcode=502&OrderId=INT10350&puramt=1773
i.e : INT10350

tduid=5c14526847651e9054552acc134e9a84&url=http://www.somedomain.co.uk/proddetails.asp?id=4204
i.e : 4204


Code I am using (Got this one from my other posting)

declare @QueryString nvarchar(255)

select@QueryString = 'ID=23456&Depatment='

selectsubstring(@QueryString, charindex('ID=', @QueryString) + 3,
charindex('&', @QueryString) - charindex('ID=', @QueryString) - 3) from Pageviews


1. But the above code only works if the string starts with 'ID='.
2. Because the col1 has strings starts with different letter this code fail to excute and gives error
3. Pathindex with regular express '(patindex('%[^0-9]%',v)-1)' cannot be used because it gets anynumber
in the string - string has mixer of numbers and letters

SO IF ANYONE LET ME KNOW HOW TO USE IF or CASE with 'charindex' or any other method to get the above said result would be greatfull.

View 18 Replies View Related

CHARINDEX AND SUBSTRINB

Jan 3, 2008

I have my column and the info is.

UserID=176&StoreID=210
sometimes there is more between the two so im tring to use a CHARINDEX and Substring

Substring(Parameters, CHARINDEX('UserID', Parameters),3)
When I do this it brings back just the 'USE' I need it to bring back the number associated with it. In this case the 176 how do i get that number?

View 2 Replies View Related

CHARINDEX Issue

Mar 4, 2008

I have used CHARINDEX successfully to search for a substring going from left to right in a string, but how do I search from the end of a string and go backwards?

Here is a sample of the problem I am trying to solve. Here is a list of cities, some with two names and some with more than two. I need a way to extract only those cities with two names. I wanted to do this by locating the first space in the string and the last space in the string. If the first space equals the last space, then the city should only be a two word city. Otherwise it is a three name city or greater. So what string functions can I use to locate the first and subsequent spaces in a string?


Here is the current version of my SQL statement:

SELECT
City.City,
CHARINDEX (' ' ,City.City) AS First_Space
FROM
City
WHERE
CHARINDEX (' ' ,City.City) <>0


AND HERE IS A SMALL SAMPLE OF WHAT IS RETURNED:

MARINE CITY7
MARINE ON SAINT CROIX7
MARION CENTER7
MARION HEIGHTS7
HIGH RIDGE5
HIGH ROLLS MOUNTAIN PARK5
HIGH SHOALS5

Thanks to all who understand and can offer usable advice in my dilemma.


Jason.

View 4 Replies View Related

Charindex Question

Mar 21, 2006

I have a field containing a string with '/' in it multiple times.How can I return the charindex of the last occurance of '/' in thestring?Regards,Ciarán

View 1 Replies View Related

PROBLEM Using CharIndex(), IF, OR Etc- PLEASE HELP

May 11, 2007

What is the best way to essentially use the charindex(find) functionif the value is could be more than one variable (A or B or C)I can't seem to get an "or", "if" or "select if" to workBelow is the code that works, I need 'GOV' to be either 'GOV' or 'FWD'or 'LIB'sqlstring = "SELECT Distinct substring([exposurename]," _& Len(Worksheets(4).Range("j5") & "_VAR_" _&Worksheets(4).Range("C4").Offset(Worksheets(4).Range("c3"), 0)) + 2 _& ",charindex('GOV',[exposurename])-" &Len(Worksheets(4).Range("j5") _& "_VAR_" &Worksheets(4).Range("C4").Offset(Worksheets(4).Range("c3"), 0)) + 3 _& ") AS Drivergrp2 " _& "FROM mars.dbo.mroInventoryProductGreeks_Latest" _& "Where producttype = 'creditdefaultswap' " _& "AND exposureName like '" &Worksheets(4).Range("j5") & "_VAR_" &Worksheets(4).Range("C4").Offset(Worksheets(4).Range("c3"), 0) & "%' "_Much appreciation if you can help

View 2 Replies View Related

CHARINDEX And STUFF/REPLACE

Jul 23, 2005

Hello,I need to be able to replace only the first occurance of a space characterin a column.Reason being is the data in the column I am trying to replace seems to haveumpteen space characters after each entry, so a simple replace functionwill replace all the spaces after it with what I want!I have thought of RTRIM to get rid of the spaces after and then replace, Ihave also thought of CHARINDEX to find the first occurance of a space andSTUFF to replace it.I have done my homework on these functions!But I am having trouble writing such a statement,I've never written a query which would use more then one function on onecolumn you see and I am getting confused!I'll tell you what I want to do in simple stepsReplace only the first found space in a name column, but then if a name hasa middle initial that will be a problem,Replace that with a dot.then concatanate '@emailaddress;@emailaddress2' after itso when SQLServer does the select it will bring back something likejoe.bloggs@emailaddress;emailaddressBut I guess I'd also need joe.n.bloggs@emailaddress;emailaddressThe data in the column looks like this at the momentjoe bloggsBut I guess there may come a time when we havejoe n bloggs, just to complicate things!What is your advice, and how do I write a query like thisI have been playing around with it in Query Analyser but as I said I amgetting confused and need some help if you don't mindThanks a lot to all who reply :-)RegardsJayne

View 2 Replies View Related

Sql Charindex Split String

Jul 23, 2005

HelloI am quite hopeless and of course a newbe.The situation: Sql2k / queryI would like it ot break down the following string:2004 Inventory:Ex.Plant Farm1:1st Cut:Premium:0094Whereby:Year = '2004 Inventory'plant= 'Ex.Plant Farm1'cut = '1st Cut'grade = 'Premium'lot# = '0094'It is always seperate by ':', but it can be 5 fields or 4 or 3 and sooncode to create the view:CREATE VIEW dbo.TESTASSELECT FullName, LEFT(FullName, CHARINDEX(':', FullName + ':') -1) AS year, CASE WHEN LEN(FullName) - LEN(REPLACE(FullName, ':', ''))[color=blue]> 0 THEN LTRIM(SUBSTRING(FullName,[/color]CHARINDEX(':', FullName) + 1, CHARINDEX(':', FullName + ':',CHARINDEX(':', Fullname) + 1) - CHARINDEX(':',FullName) - 1)) ELSE NULL END AS Plant, CASEWHEN LEN(FullName) - LEN(REPLACE(FullName, ':', '')) > 1 THENLTRIM(SUBSTRING(FullName,CHARINDEX(':', FullName + ':', CHARINDEX(':',FullName) + 1) + 1, CHARINDEX(':', FullName + ':', CHARINDEX(':',Fullname) + 1) - CHARINDEX(':',FullName+':') - 1)) ELSE NULL END AS [Cut]FROM dbo.ItemInventoryCan anyone help me with this? I am stuck half the way and get for cutthe rest of the string: '1st Cut:Premium:0094'Thanks!

View 5 Replies View Related

Transact SQL :: Converting A Value Using Charindex

Jul 10, 2015

What is the best way to convert 3/1/1/12/0 into xxx-xx-xx-xx-xx format by appending zeros if required. final result should be
300/10/10/12/00.

View 9 Replies View Related

Parse A String Using Charindex

Jan 15, 2008

Hi,

I've the following query. I'm using the yellow highlighted to join 2 tables, as these tables dont have a relationship between them.
The format of the name field is 'AAAA-BBBBBB-123'
here A will be only 4 chars, followed by '-' B can be any number of chars again followed by '-' and the last is the id which I'm using to do a join. This query will fail if the id is just 1 digit as its taking the last 3 chars as the id.
I dont know how to get the id from the right using charindex. Charindex would search for the first occurence of '-' from the right and get the chars after hypen i.e 123. How can this be achieved?


SELECT id AS 'ID',
name AS 'name',
sequence AS 'num'
FROM
FirstTable A
INNER JOIN SecondTable q
ON (CONVERT(INT,RIGHT(name,3))= a.id)
INNER JOIN ThridTable t
ON(t.id = q.id)
INNER JOIN FourthTable s
ON (q.name = s.name )
WHERE A.id = @ID
AND t.name=LEFT(s.name,((CHARINDEX('-',s.name))-1))
ORDER BY 'ID','num'


One more question on this is: Is this a good way of joining tables? If I dont use this I've a very large query containing unions. Which one should be bug-free and more efficient?

Thanks,
Subha

View 9 Replies View Related

CHARINDEX BUG Returns Wrong Value

Jan 8, 2008

Hi

I've got a problem which looks like it might be a bug with the CHARINDEX function for Microsoft SQL Server.

The following line of code returns TRUE (1), but you would expect it to return FALSE (0):


SELECT CHARINDEX('Prausse', 'Prauße', 1)

Is there a way around this problem?


Thanks in advance for your responses.

View 3 Replies View Related

OR-statement Returns True CHARINDEX Instead Of Name LIKE

Jun 11, 2013

I have this OR in a simple query:

Code:
DECLARE @searchString nvarchar(100)
SET @searchString = 'sample'
SELECT TOP(1) * FROM user
WHERE (user.identity LIKE @searchString OR
CHARINDEX(@searchString, user.firstname + ' ' + user.lastname) > 0)
PS: Handwritten...

If I pass in a searchString that matches the Identity and a different users lastname, this query will return the user with the lastname-match (which is wrong in my eyes, it should have matched the Identity first, then returned that row [Identity is a Primary key, indexed non-clustered]).

I've tried various things:
Removing LastName: (CHARINDEX(@searchString, user.firstname + ' ') > 0), then the returned row is from a matching identity, due to the lastname of a user was a match, but lastname was removed...so :P
Flipping the conditions around
Adding/removing paranthesis... without any luck.

Is there some option somewhere, to force the OR statement to return on the first true condition. I've always thought OR-statements (in a computer that is) breaked and returned true on the first true condition it found (from left to right, not bother to check the rest of the conditions...)?Or do I have to rewrite the query, with an IF, checking if the @searchString is a valid identity-format, if it is, query on the identity, if not query on the username...?

View 12 Replies View Related

CHARINDEX With INT Data Type (Multiple Value)

Mar 24, 2014

I have a column that has 50 records and they are INT. I am trying to place them into a single parameter using the CHARINDEX using the IF Statement. I got an error saying convertinh from varchar to int type data.

Basically, this is what I did:
@RoomID varchar(max)

Then I declare it:

DECLARE @RoomId varchar(4)

SET @RoomID = 0

The IF part that I need to express this CHARINDEX function.

Then in Where clause I filtered it as:
WHERE r.roomid = @RoomId

Or what other way to handle INT data type and make them available for user to choose multiple value?

View 1 Replies View Related

Substring And Charindex Script Not Working

May 24, 2006

This script doesn't work. Why?UPDATE [460zz_Relma_Comment_Parse]SET [Comments 1] = LTRIM(SUBSTRING([Comments], 1,convert(bigint, CHARINDEX(',', Comments)-1)))WHERE NOT([COMMENTS] IS NULL) AND LEN([Comments]) > 8Basically, I'm trying to move everything before a comma into [Comments1] and everything after the comma into [Comments 2]. The comments 2script works. See below.UPDATE [460zz_Relma_Comment_Parse]SET[Comments 2] = LTRIM(SUBSTRING([Comments], convert(bigint,charindex(',', [Comments])+1), Len([Comments]) - charindex(',',[Comments])))WHERE NOT([COMMENTS] IS NULL) AND LEN([Comments]) > 8This script [Comments 2] runs perfectly but the first one [Comments 1]above gives me the following error.Msg 536, Level 16, State 5, Line 1Invalid length parameter passed to the SUBSTRING function.The statement has been terminated.They are basically the same script except I'm adding +1 to one scriptand minusing one -1 from the other.Thanks,db55

View 1 Replies View Related

The Following Prints Out 0 - SQL Procedure And Use Of The Charindex Function.

Jul 20, 2005

My code prints out 0 for the value of charindex ( 'Hello.', '.' ).Did I miss something? I think it should print out 6!

View 1 Replies View Related

Transact SQL :: Can Add 1 To Charindex Function But Can't Minus 1

Aug 25, 2015

The charindex can run this

LEFT([Description], CHARINDEX('(', [Description]) + 1)  as NewDesc,

But I can't run

LEFT([Description], CHARINDEX('(', [Description]) - 1)  as NewDesc,

View 5 Replies View Related

Why Is Left Table In LEFT JOIN Limited By Where Clause On Right Table

Jan 25, 2015

-- Why is the left table in a LEFT JOIN limited by the where clause on the right table?eg

DECLARE @LeftTable TABLE (LeftID INT NOT NULL IDENTITY(1, 1), LeftValue INT NULL)
INSERT @LeftTable (LeftValue)
VALUES (111)
INSERT @LeftTable (LeftValue)
VALUES (222)

[code]....

View 2 Replies View Related

Help: About Charindex Function Doesn't Work With Variable

May 23, 2007

Hello to all,
I hope that somebody can help me.
I have written a sql query to search Partner.  I have a wtcomValidRelationships Table. There are two Fields (IDMember(type: Int) and RelationshipIDs(type: varchar(1000)) in this table.
Example: 3418 has 3422 RelationshipID and 3422 has 4088 RelationshipID, if i want to check if there is a relationship between 3418 and 4088. 
declare @IDM int;
declare @IDO char(100);
set @IDM = 3418;
set @IDO = '4088';
select B.IDMember
from wtcomValidRelationships as A, wtcomValidRelationships as B
where A.IDMember = @IDM and charindex(cast(B.IDMember as char(100)),A.RelationshipIDS) > 0
and charindex(@IDO,B.RelationshipIDs) > 0
Using this query i get nothing.
I try to use constant in charindex and i get result.
declare @IDM int;
declare @IDO char(100);
set @IDM = 3418;
set @IDO = '4088';
select B.IDMember
from wtcomValidRelationships as A, wtcomValidRelationships as B
where A.IDMember = @IDM and charindex('3422',A.RelationshipIDS) > 0
and charindex('4088',B.RelationshipIDs) > 0
So i think that charindex doesn't work with variable. But I must use variable. Can someone help me? What should i do ?
Thanks
Best Regards
Pinsha

View 1 Replies View Related

T-SQL (SS2K8) :: How To Use Substring And Charindex To Extract Desired String

Jul 9, 2014

I have a column that contains the follwoing string I need to compare.

ek/df/cv/
ek/df/cv/f

All fields bfore the third / are not fixed but behind the third/ is eiter nothing or one letter I need a function to extract all the fields before the third / to compare if they are equal.

I can't do it by using the combination of Substring() and charindex() and Len()

View 9 Replies View Related

T-SQL (SS2K8) :: Trying To Use Substring (charindex) To Remove Start Of A String

Aug 26, 2014

Looking at a trace table and trying to remove all the "erroneous" bits in a string e.g the declares etc so I can purely get to proc names.

An example string

declare @p2 varchar(10) set @p2=NULL exec sp_proc @Code='TF',@TypeCode=@p2 output select @p2

I've tried

select top 5000 textdata,substring(textdata,charindex('exec',textdata)+5,charindex('@',textdata)-1)
from trace_table
where TextData like '%sp_%'
and TextData like '%declare%'

And it fails dismally...

View 8 Replies View Related

Extract IP Address From Command String - Subscript And Charindex

Apr 21, 2014

I am trying to extract the IP address from a command string, the problem I am running into is there are 3 types of command strings.

SENDAUTO IP192.168.1.32L0O11 Z1 5(E=00:00,F=00:00,G=00:00,H=00:00,I=00:00,J=00:00)

SENDCREATEEXCEPTION -1,IP192.168.1.32,0,11,0,Z1,Free text-label,19,3,19,3,06:00|24:00,I|O,1,288003,1

SENDWEEKTIMES IP192.168.1.32,0,11,Z1,3,100,23:00|24:00|24:00|24:00|24:00|24:00,I|O|O|O|O|O

The IP address length can vary, and the character after the IP is either a L or ,

How can I edit the following function to look for both characters?

SUBSTRING(Command, CHARINDEX('IP', Command), CHARINDEX('L', Command) - (CHARINDEX('IP', Command)))

View 6 Replies View Related







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