Sql Charindex Split String
Hello
I am quite hopeless and of course a newbe.
The situation: Sql2k / query
I would like it ot break down the following string:
2004 Inventory:Ex.Plant Farm1:1st Cut:Premium:0094
Whereby:
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 so
on
code to create the view:
CREATE VIEW dbo.TEST
AS
SELECT 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, CASE
WHEN LEN(FullName) - LEN(REPLACE(FullName, ':', '')) > 1 THEN
LTRIM(SUBSTRING(FullName,
CHARINDEX(':', FullName + ':', CHARINDEX(':',
FullName) + 1) + 1, CHARINDEX(':', FullName + ':', CHARINDEX(':',
Fullname) + 1) - CHARINDEX(':',
FullName+':') - 1)) ELSE NULL END AS [Cut]
FROM dbo.ItemInventory
Can anyone help me with this? I am stuck half the way and get for cut
the rest of the string: '1st Cut:Premium:0094'
Thanks!
View Complete Forum Thread with Replies
Related Forum Messages:
- Parse A String Using Charindex
-
How To Split A String Using Sql
- Split A String
- Split A String In Sql
- How To Split The String
-
How To Split A Delimeted String...
-
SQL String Split With | Pipe
- Split The String Into Columns
- Split String Using Delimiter
- How To Split A Comma In A String
- Split Command In String
- SPLIT A String Inside SSIS/T-SQL Code?
-
How Do I Split And Insert A Comma Delimited String To A Table?
- CHARINDEX
- Using CHARINDEX Vs LIKE In WHERE?
- Charindex Question
- PROBLEM Using CharIndex(), IF, OR Etc- PLEASE HELP
- IN Clause And CharIndex
- Charindex And Substring
- Substring, Charindex, ??
- Help With SUBSTRING, CHARINDEX
- CHARINDEX AND SUBSTRINB
- How To Use IF Or Case With Charindex?
- CHARINDEX Issue
- CHARINDEX And STUFF/REPLACE
- CharIndex, Left T-SQL Question
- SQL7 Charindex Behavioural Changes
- CHARINDEX BUG Returns Wrong Value
- Substring And Charindex Script Not Working
-
Help: About Charindex Function Doesn't Work With Variable
-
Alternative For LEFT() And CHARINDEX() That Works With Text Data Type
- The Following Prints Out &"0&" - SQL Procedure And Use Of The &"charindex&" Function.
- Employing XML Formatted String Data Rather Than Normal String(char(), Nchar() Or Varchar() Values
- String Or Binary Data Would Be Truncated. (only For 1700 Character String?)
- Name Split
- Name Split
- Split Value In Sql
- To Split Or Not To Split
- SPLIT() UDF
-
Adding String To Database, But Name Of String Is Added, Not Data
-
Help: About Ms Sql Query, How Can I Check If A Part String Exists In A String?
- Capitalize A Text String/String Function Related
- Need Help With String Manipulation - Splitting 1 String Into Multiple Columns
-
SQL Search Split
-
Reg Split Funtion
- Split A Field
- Split A Column
Parse A String Using Charindex
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 Replies !
How To Split A String Using Sql
I have 5 dynamic rows each row consisting of 5 checkboxes & 5 dropdowns.I am concatenating the values of each controls in a row using a wildcard charater "~" and each row i am concatenating using "|".The complete string is then assigned to one hidden field and passed as sql parameter to the backend. Please help in writing the split function to get the values of each checkboxes and dropdowns from the string in order to save them in separate columns. Thanks
View Replies !
Split A String
Hi I have this string which might have a hyphen in it "-" What I want to do is if I get a hyphen then take all characters after hyphen else take only all the characters starting from the 5th position of the string How can this be achieved?
View Replies !
Split A String In Sql
Hi I need a stored procedure in SQL that will split a comma separated variable passed to it select a name for each value and return a recordset. Any pointers greatfully received. First attempt is dreadfully slow as I am opening recordsets each time Function func_getFood() Dim rsfoodsql Dim foodoutput for x=1 to ubound(masterfoodarray)-2 set rsfoodsql= objconn.execute ("select foodname from tbl"&language&"food where foodID='"& masterfoodarray(x) &"'") if not rsfoodsql.eof then foodoutput=rsfoodsql("foodname") if not foodoutput="" then response.write foodoutput&"<BR>" end if end if next End Function Hope someone can help, cheers
View Replies !
How To Split The String
I am having City, State i need to split these two string with comma separated and to search based on the city and state how to write the select query any one know help me Regards, Prabu R
View Replies !
How To Split A Delimeted String...
hi, i have a simple question, i have a sql server table named "Restaurant" and a field "Cuisines", the values in the field Cuisines contains delimeted string. (e.g. "C1,C2,C3...C10" ,maximum to 10 items or less) now, i want to split the values from Cuisines ("C1,C2,C3...C10") and passed all of them to a SP parameter. e.g @item0 nvarchar = "C1",@item1 nvarchar = "C2",@item2 nvarchar = "C3",@item3 nvarchar = "C4",@item4 nvarchar = "C5",@item5 nvarchar = "C6",@item6 nvarchar = "C7",@item7 nvarchar = "C8",@item8 nvarchar = "C9",@item9 nvarchar = "C10" if the field "Cuisines" contains less than 10 items, the value of the remaining parameters is null. any response will be appreciated. thanks.
View Replies !
SQL String Split With | Pipe
I've got a dilemma here. I'm currently reading records into EasyListBox (ELB) dropdownlist. The criteria in the dropdownlist is based on the select from another ELB dropdownlist. The problem is that the data contains rows with pipes that serve as separters. For example, one of the options that comes back now might be 123 | 456 | 789. I need to be able to make each of them its own row in the dropdownlist. Can anyone advice? Most records don't have any pipes and come throught fine, but some dont. My code below: Dim sAT As String = Replace(elbAttribute.SelectedValue, "'", "''") Dim adapter As New SQLDataAdapter("Select Feature_Type As Attribute_Name, FEATURE_TEXT_VALUE as Attribute_Value, (select distinct FILTER_FAMILY_FEATURE_EXCLUDED.FEATURE_TYPE_ID from FILTER_PROFILES, FILTER_FAMILY_FEATURE_EXCLUDED, FAMILY_ALLOWED_FEATURE_TYPES, SHARED_FEATURE_TYPES, SHARED_FEATURE_VALUES where FILTER_PROFILES.FILTER_PROFILE_NAME = 'MAQ' And FILTER_PROFILES.FILTER_PROFILE_ID = FILTER_FAMILY_FEATURE_EXCLUDED.FILTER_PROFILE_ID And FAMILY_ALLOWED_FEATURE_TYPES.FAMILY_ID = FILTER_FAMILY_FEATURE_EXCLUDED.FAMILY_ID And FILTER_FAMILY_FEATURE_EXCLUDED.FEATURE_TYPE_ID = SHARED_FEATURE_TYPES.FEATURE_TYPE_ID And (SHARED_FEATURE_TYPES.Feature_Type_ID = SHARED_FEATURE_VALUES.Feature_Type_ID And left(FEATURE_TYPE, 4) <> 'CPLV' And Feature_Type = '" & sAT & "')) As ExclusionFlag From SHARED_FEATURE_TYPES, SHARED_FEATURE_VALUES, PRODUCT_FEATURE_VALUES Where PRODUCT_FEATURE_VALUES.FEATURE_VALUE_ID = SHARED_FEATURE_VALUES.Feature_Value_ID And SHARED_FEATURE_TYPES.Feature_Type_ID = SHARED_FEATURE_VALUES.Feature_Type_ID And left(FEATURE_TYPE, 4) <> 'CPLV' And Feature_Type = '" & sAT & "' UNION Select distinct Column_Name As Attribute_Name, SMALL_TEXT_VALUE As Attribute_Value, (select FILTER_ATTRIBUTES_EXCLUDED.EXT_ATT_ID from FILTER_PROFILES, FILTER_ATTRIBUTES_EXCLUDED where FILTER_PROFILES.FILTER_PROFILE_NAME = 'MAQ' And FILTER_PROFILES.FILTER_PROFILE_ID = FILTER_ATTRIBUTES_EXCLUDED.FILTER_PROFILE_ID And FILTER_ATTRIBUTES_EXCLUDED.EXT_ATT_ID = EXTENDED_ATTRIBUTES.EXT_ATT_ID) As ExclusionFlag From EXTENDED_ATTRIBUTE_VALUES, EXTENDED_ATTRIBUTES, PRODUCTS Where PRODUCTS.PRODUCT_ID = EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID And not SMALL_TEXT_VALUE is null And EXTENDED_ATTRIBUTE_VALUES.EXT_ATT_ID > 1499 And EXTENDED_ATTRIBUTE_VALUES.EXT_ATT_ID = EXTENDED_ATTRIBUTES.EXT_ATT_ID And Column_Name = '" & sAT & "'", myConnection) Dim dt As New DataTable() adapter.Fill(dt) elbValue.DataSource = dt elbValue.DataBind()
View Replies !
Split The String Into Columns
I have a table called products with the values like ProductId ProductName 10 A 20 D,E,F,G 30 B,C 40 H,I,J I need to display each productid's with ProductId ProductName 10 A 20 D 20 E 20 F 20 G 30 B 30 C 40 H 40 I 40 J I will be appreciated if you can send me the code. Thanks, Mears
View Replies !
Split String Using Delimiter
Hi, I get a string whihc looks like 'Q306/Q406 Version1/Current/Q108 Version2' I need to split the above string and get each of those values... ' / ' delimiter Can some one please help on this. Thanks
View Replies !
Split Command In String
hi all, i am still a newbie in sql i got a problem with my query for example: ------------------------------- DECLARE @LongString VARCHAR(10) @LongString = "Hello-Word" ------------------------ i want to change the LongString value by removing the "-" however i i need to identify if the @longString got "-" and delete it if it found how do i do that in sql Thanks a lot guys arifliminto86
View Replies !
SPLIT A String Inside SSIS/T-SQL Code?
I have a RPC which gives me multiple - single record rows like Robert|K|Half|TX|1123823|1423904 -- This is one such record that i get in 1 Column Now I need to split the above record into 6 Fields and populate in my local DB I know i could use any .NET Language and accomplish this. But Iam limited to using SSIS/T-SQL Proc's Any ideas / directions?
View Replies !
CHARINDEX
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 Replies !
Using CHARINDEX Vs LIKE In WHERE?
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 Replies !
Charindex Question
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 Replies !
PROBLEM Using CharIndex(), IF, OR Etc- PLEASE HELP
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 Replies !
IN Clause And CharIndex
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 Replies !
Charindex And Substring
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 Replies !
Substring, Charindex, ??
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 Replies !
Help With SUBSTRING, CHARINDEX
I have a record with seven pieces of data, separated by commas: a, b, c, d, e, f, g I'm looking for some assistance on a good way to query the data into seven columns in the same result set or temp table (which will then ultimately be transformed to a CSV file for a required report). I've used a combination of SUBSTRING, CHARINDEX, LEFT, and LEN and found several ways to separate the data into separate temp tables, but no way to get it into separate columns in the same table or result set. Any advise would be most appreciated. Steve Jaeckels
View Replies !
CHARINDEX AND SUBSTRINB
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 Replies !
How To Use IF Or Case With Charindex?
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 Replies !
CHARINDEX Issue
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 Replies !
CHARINDEX And STUFF/REPLACE
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 Replies !
CharIndex, Left T-SQL Question
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 donot.We are trying to evaluate against any data in the'options.optionDescrip' column located to the left of a comma (if acomma does exist, which it may not). If no comma exists, then we tryand evaluate against the entire field, not just the part to the leftof the comma.SELECT options_optionsGroups.idProduct FROM options_optionsGroupsJOIN Options ON options_optionsGroups.idOption=options.idOptionJOIN products ON options_optionsGroups.idProduct=products.idProduct WHERE (CASE WHEN CharIndex(',',options.optionDescrip) = 0 THENoptions.optionDescrip LIKE '" & gauge & "%' ELSELeft(options.optionDescrip,CharIndex(',',options.o ptionDescrip)) LIKE'" & gauge & "%' END)Thanks for any input you can provide, I appreciate it.
View Replies !
SQL7 Charindex Behavioural Changes
Folks, when converting from SQL6.5 to 7.0, I have noticed a change in behaviour with the charindex if the datatypes used in the comparison are not the same. Sample code: create table x1 (col1 varchar(10), col2 int) go insert into x1 select 'monday', 10 insert into x1 select 'tuesday', 20 go declare @x char(10) select @x = 'monday' select res = charindex(@x,col1) * col2 ,col1 ,col2 from x1 go If you declare @x as varchar(10) not char(10), the sucker works (ie "res" comes back as 10 for monday and zero for tuesday not zero for both). In an ideal world, there would be some undocumented setting somewhere that means I don't have to review 250+ procs before xmas!! I can't see anything in BOL or the KB about this particular issue. Cheers Si
View Replies !
CHARINDEX BUG Returns Wrong Value
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 Replies !
Substring And Charindex Script Not Working
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 Replies !
Help: About Charindex Function Doesn't Work With Variable
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 Replies !
Alternative For LEFT() And CHARINDEX() That Works With Text Data Type
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 Replies !
String Or Binary Data Would Be Truncated. (only For 1700 Character String?)
I am trying to insert a row into a table of Microsoft SQL Server 2000. There are various columns. [SNO] [numeric](3, 0) NOT NULL , [DATT] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [DATTA] [char] (3000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [CODECS] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , The [DATTA] column is causing a problem. Even if I am trying to put only 1700 character string into [DATTA], the java code throws the following exception:- StaleConnecti A CONM7007I: Mapping the following SQLException, with ErrorCode 0 and SQLState 08S01, to a StaleConnectionException: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Connection reset at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source) Why is it throwing an exception even though the sum-total of this row doesn't exceed 8000 characters? Can anyone please tell me what's wrong?
View Replies !
Name Split
Quick question. I've got a CHAR (70) field called NAME that has a first and last name separated by a space. I want to split it into two fields FIRST and LAST -- with all the characters to the left of the space a first name and all the characters to the right of the space as last name. I couldn't find a string function that would let me do this simply (it may be right in front of me and I missed it). Thanks in advance. Ray
View Replies !
Name Split
I need to split a column of Full Names into First name and Last name columns. Has someone come across this before and if so can you give me an idea of how to overcome it?
View Replies !
Split Value In Sql
Hi to all I have one problem regarding sp and pass value in sp I am gating a value like Abc,Def,Ghi, Now I want to split the whole pass value by “,� And fire one for loop to store value in database This things is done in asp.net web form but I want to do all process in sp So please guide me how I am write sp . The purpose is pass value one time so connection time is decrees and give fast perforce
View Replies !
To Split Or Not To Split
I have a database with a "large" table containing date based information Basically they're reservations. I've thought about creating a new table and adding any records from past years to this table. For the most part only current reservation need to be searchable, but in some circumstances it would be useful to be able to search through the archive too. so, my questions!!! Is 8,000 or so rows of data "large" and unwieldly in SQL terms? Would splitting this data into 2 tables - one small table for current and future reservations and one larger archive table then using a UNION SELECT query to make archive information seachable be a significant improvment on server resources/load or am I making the whole thing more complicated than it need be as 8,000 rows of data is nothing to worry about............. What did they say about a little bit of knowledge being a dangerous thing? Thanks in advance of any guidance to a neophyte!!?
View Replies !
SPLIT() UDF
SQL UDF split() The objective of this article is to help the SQL developers with an UDF that can be used within a stored procedures or Function to split a string (based on given delimiter) and extract the required portion of the string. Scripting languages like VB script and Java script have in-built split() functions but there is no such function available in SQL server. In my experience this function is really handy when you’re working on an ASP application with SQL server as backend, whereby you’ll need to pass the ASP page submitted values to the SQL stored procedure. To give a simple example, in a typical Monthly reporting ASP page – the users would select a range of months and extract the information pertaining to this date range. Classic implementation of this model is to have an ASP page to accept the input parameters and pass the values to the SQL stored procedure (SP). The SP would return a result set which is then formatted in the ASP page as results. If the date range is continuous ie. JAN07 to MAR07 then the SP can typically accept a ‘From’ and ‘To’ range variables. But I’ve encountered situations whereby the users select 3 months from the current year and 2 months from previous year (non-continuous date ranges). In such scenario the SP cannot have a date range as input parameters. Typically an ASP programmer would do is by having a single date input parameter in the SP and call the SP within a loop in the ASP page. This is an inefficient way of programming as contacting the database server within an ASP loop could cause performance overhead especially if the table being queried is an online transaction processing table. Here is how I handled the above situation. 1.Declared one string input parameter of type varchar(8000) (if you’re using SQL 2005 then it is advisable to use Varchar(Max)) 2.Pass the ASP submitted values as string, in this case the months selected by user would be supplied to the SP as a string 3.Within the Stored Procedure I’ll call the split() function to extract each month from the string and query the corresponding data The basic structure of the stored procedure is as pasted below:- CREATE PROCEDURE FETCH_SALES_DETAIL ( @MONTH VARCHAR(MAX) ) AS BEGIN DECLARE @MONTH_CNT INT,@MTH DATETIME SET @MONTH_CNT=1 WHILE DBO.SPLIT(@MONTH,',',@MONTH_CNT) <> '' BEGIN SET @MTH = CAST(DBO.SPLIT(@MONTH,',',@MONTH_CNT) AS DATETIME) --<<Application specific T-SQLs>>-- (BEGIN) SELECT [SALES_MONTH],[SALES_QTY],[PRODUCT_ID],[TRANSACTION_DATE] FROM SALES (NLOCK) WHERE [SALES_MONTH]= @MTH --<<Application specific T-SQLs>>--(END) SET @MONTH_CNT=@MONTH_CNT+1 END END Dbo.SPLIT() function takes 3 parameters 1)The main string with the values to be split 2)The delimiter 3)The Nth occurrence of the string to be returned The functionality of the UDF is as explained STEP by STEP: 1.Function Declaration CREATE FUNCTION [dbo].[SPLIT] ( @nstring VARCHAR(MAX), @deliminator nvarchar(10), @index int ) RETURNS VARCHAR(MAX) Function is declared with 3 input parameters:- @nstring of type VARCHAR(MAX) will hold the main string to be split @deliminator of type NVARCHAR(10) will hold the delimiter @index of type INT will hold the index of the string to be returned 2.Variable Declaration DECLARE @position int DECLARE @ustr VARCHAR(MAX) DECLARE @pcnt int Three variables are needed within the function. @position is an integer variable that will be used to traverse along the main string. @ustr will store the string to be returned and the @pcnt integer variable to check the index of the delimiter. 3.Variable initialization SET @position = 1 SET @pcnt = 1 SELECT @ustr = '' Initialize the variables 4.Main functionality WHILE @position <= DATALENGTH(@nstring) and @pcnt <= @index BEGIN IF SUBSTRING(@nstring, @position, 1) <> @deliminator BEGIN IF @pcnt = @index BEGIN SET @ustr = @ustr + CAST(SUBSTRING(@nstring, @position, 1) AS nvarchar) END SET @position = @position + 1 END ELSE BEGIN SET @position = @position + 1 SET @pcnt = @pcnt + 1 END END 4.1The main while loop is used to traverse through the main string until the word index is less than or equal to the index passed as input parameter. 4.2Within the while loop each character within the string is verified against the delimiter and if it does not match then local word count variable is checked against the input index parameter 4.3If the values are same ie., the input variable index and the word being processed in the while loop are the same then the word is stored in the @ustr variable. If the values does not match then the @position variable is incremented. 4.4If the character matches with the delimiter then the word count variable @pcnt is incremented along with the @position variable 5.Return the value RETURN @ustr I hope this article would benefit those who are looking for a handy function to deal with Strings. Feel free to send your feedback at dearhari@gmail.com
View Replies !
Adding String To Database, But Name Of String Is Added, Not Data
Hello, I am tring to add a string my database. Info is added, but it is the name of the string, not the data contained within. What am I doing wrong? The text "Company" and "currentUserID" is showing up in my database, but I need the info contained within the string. All help is appreciated! Imports System.Data Imports System.Data.Common Imports System.Data.SqlClientPartial Class _DefaultInherits System.Web.UI.Page Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizard1.CreatedUser 'Database ConnectionDim con As New SqlConnection("Data Source = .SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|ASPNETDB.mdf;user instance=true") 'First Command DataDim Company As String = ((CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Company"), TextBox)).Text) Dim insertSQL1 As StringDim currentUserID As String = ((CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox)).Text) insertSQL1 = "INSERT INTO Company (CompanyName, UserID) VALUES ('Company', 'currentUserID')"Dim cmd1 As New SqlCommand(insertSQL1, con) '2nd Command Data Dim selectSQL As String selectSQL = "SELECT companyKey FROM Company WHERE UserID = 'currentUserID'"Dim cmd2 As New SqlCommand(selectSQL, con) Dim reader As SqlDataReader '3rd Command Data Dim insertSQL2 As String insertSQL2 = "INSERT INTO Company_Membership (CompanyKey, UserID) VALUES ('CompanyKey', 'currentUserID')"Dim cmd3 As New SqlCommand(insertSQL2, con) 'First CommandDim added As Integer = 0 Try con.Open() added = cmd1.ExecuteNonQuery() lblResults.Text = added.ToString() & " records inserted."Catch err As Exception lblResults.Text = "Error inserting record." lblResults.Text &= err.Message Finally con.Close() End Try '2nd Command Try con.Open() reader = cmd2.ExecuteReader()Do While reader.Read() Dim CompanyKey = reader("CompanyKey").ToString() Loop reader.Close()Catch err As Exception lbl1Results.Text = "Error selecting record." lbl1Results.Text &= err.Message Finally con.Close() End Try '3rd Command Try con.Open() added = cmd3.ExecuteNonQuery() lbl2Results.Text = added.ToString() & " records inserted."Catch err As Exception lbl2Results.Text = "Error inserting record." lbl2Results.Text &= err.Message Finally con.Close()End Try End Sub End Class
View Replies !
Help: About Ms Sql Query, How Can I Check If A Part String Exists In A String?
Hello to all, I have a problem with ms sql query. I hope that somebody can help me. i have a table "Relationships". There are two Fields (IDMember und RelationshipIDs) in this table. IDMember is the Owner ID (type: integer) und RelationshipIDs saves all partners of this Owner ( type: varchar(1000)). Example Datas for Table Relationships: IDMember Relationships . 3387 (2345, 2388,4567,....) 4567 (8990, 7865, 3387...) i wirte a query to check if there is Relationship between two members. Query: Declare @IDM int; Declare @IDO int; Set @IDM = 3387, @IDO = 4567; select * from Relationship where (IDMember = @IDM) and ( cast(@ID0 as char(100)) in (select Relationship .[RelationshipIDs] from Relationship where IDMember = @IDM)) But I get nothing by this query. Can Someone tell me where is the problem? Thanks Best Regards Pinsha
View Replies !
Capitalize A Text String/String Function Related
Hi Folks: How can I capitalize a string like 'JOHN DOE' into 'John Doe' with one SQL statement. SQL does provide string function like LOWER(char_expr) which would change the whole text string to 'john doe' and I don't want that. So far, in order to do that, I have to use a front-end development language like 'Omnis' which has a string function 'cap()' to capitalize the whole string, then update the back-end SQL with the new string. Thank you in advance for your time and advice. David Nguyen
View Replies !
Need Help With String Manipulation - Splitting 1 String Into Multiple Columns
Hello All, I'm a non-programmer and an SQL newbie. I'm trying to create a printer usage report using LogParser and SQL database. I managed to export data from the print server's event log into a table in an SQL2005 database. There are 3 main columns in the table (PrintJob) - Server (the print server name), TimeWritten (timestamp of each print job), String (eventlog message containing all the info I need). My problem is I need to split the String column which is a varchar(255) delimited by | (pipe). Example: 2|Microsoft Word - ราย�ารรับ.doc|Sukanlaya|HMb1_SD_LJ2420|IP_192.10.1.53|82720|1 The first value is the job number, which I don't need. The second value is the printed document name. The third value is the owner of the printed document. The fourth value is the printer name. The fifth value is the printer port, which I don't need. The sixth value is the size in bytes of the printed document, which I don't need. The seventh value is the number of page(s) printed. How I can copy data in this table (PrintJob) into another table (PrinterUsage) and split the String column into 4 columns (Document, Owner, Printer, Pages) along with the Server and TimeWritten columns in the destination table? In Excel, I would use combination of FIND(text_to_be_found, within_text, start_num) and MID(text, start_num, num_char). But CHARINDEX() in T-SQL only starts from the beginning of the string, right? I've been looking at some of the user-defind-function's and I can't find anything like Excel's FIND(). Or if anyone can think of a better "native" way to do this in T-SQL, I've be very grateful for the help or suggestion. Thanks a bunch in advance, Chutikorn
View Replies !
SQL Search Split
CREATE PROCEDURE [dbo].[ShowComboLocation]@Keyword varchar(50) ASSELECT TOP 100 PERCENT PropertyAreaID, PropertyAreaFROM dbo.iViewAllWHERE (PropertyArea LIKE '%' + @Keyword + '%')GOQuestion 1 isIf Keyword ="London WestEnd Harrods", I know my query will end up like this (PropertyArea LIKE 'London WestEnd Harrods')But I want to to individually search for 3 or 1-nth words therefore my query should end up like this(PropertyArea LIKE 'London')OR (PropertyArea LIKE 'WestEnd')OR (PropertyArea LIKE 'Harrods')i WANT TO perform this on my SQL STored Procedure,Can anybody provide code or links pls
View Replies !
Reg Split Funtion
Hi, Is it possible to split the following value in sql server ? I have the value like 25 Email Accounts,50 Email Accounts in my sqlserver database. Here i need only the numeric value .ie 25,50.Is it possible? can any one give me the solution .. I am using ASP.Net and C# backend is SQL Server 2000. Thanks and Regards Arul
View Replies !
Split A Field
Whats the best way to do the following?Field1 in Table1 contains numbers and characters seperated by #Examples: aaa#01, kjhkjhjh#21 and jlkjlkj#123How can I create two new fields in Table1, one containing what is tothe left of the # and the other what is to the right?Regards,Ciarán
View Replies !
Split A Column
Hi everybody Does any body know how to split a field in a table into two fields eg usermaster(table) userid(field) usermaster has 40 users with user id 1 to 40 i want to get data as userid userid 1 21 2 22 3 23 . . . . . . 20 40 Thanks you very much
View Replies !
|