SQL Trim after first space [closed] - tsql

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I need to Trim everything after the first space in a string.
Example: Asprin Oral
I just need Asprin.

In TSQL:
declare #test varchar(30)
select #test = 'Asprin Oral'
select substring(#test, 1, charindex(' ', #test + ' ')-1)
or like #GilM stated:
declare #test varchar(30)
select #test = 'Asprin Oral'
select LEFT(#test, CHARINDEX(' ', #test+' ')-1)

You could do a String.Split(' ') on spaces and take the [0] position of the result.
String.Split()

Related

How to give an alias name with a space in sparksql [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i have tried below codes
trial-1
..........
val df2=sqlContext.sql("select concat(' ',Id,LabelName) as 'first last' from p1 order by LabelName desc ");
trial-2
.........
val df2=sqlContext.sql("select concat(' ',Id,LabelName) from p1 order by LabelName desc ");
val df3=df2.toDF("first last")
trial-1 is throwing error when i tried to run it.......but in trial-2 it is taking the command but throwing the error when i performed below action
scala> df3.write.parquet("/prashanth/a1")
When a SQL column contains special characters in a SQL statement, you can use `, such as `first last`.
You cannot use space in a Parquet column. You can either rename the column or use other file format, such as csv.

Extract text, Matlab [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to find a way to extract text in a specific and efficient way
as in this example:
'Hello Mr. Jack Andrew , your number is 894Gfsf , and your Bank ID # 734234"
I want a way to get the Name, the Number and the Bank ID Number.
I want to write software that deals with different text files and get those required values. I may not know the exact order but it must be a template like a bank statement or something.
Thanks!
It's a bit hard to understand what exactly is the problem.. If all you need to do is to split strings, here's a possible way to do it:
str = 'Hello Mr. Jack Andrew , your number is 894Gfsf , and your Bank ID # 734234';
tokenized = strsplit(str,' ');
Name = strjoin([tokenized(3:4)],' ');
Number = tokenized{9};
Account = tokenized{end};
Alternatively, for splitting you could use regexp(...,'split') or regexp(...,'tokens');
I think you want regular expressions for this. Here's an example:
str = 'Hello Mr. Jack Andrew , your number is 894Gfsf , and your Bank ID # 734234';
matches=regexp(str, 'your number is (\w+).*Bank ID # (\d+)', 'tokens');
matches{1}
ans =
'894Gfsf' '734234'
My suggestion would be to make a whole array of strings with sample patterns that you want to match, then build a set of regular expressions that collectively match all of your samples. Try each regexp in sequence until you find one that matches.
To do this, you will need to learn about regular expressions.

How to retrieve the values of required keys in Perl [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a hash with keys and values. How can I retrieve the values of the desired keys?
%a = qw(genea brain geneb heart genec kidney gened eye);
Now I want to retrieve the value for the keys genec and gened. How can I do this?
To get a list of the values for many keys at once, use a hash slice:
#lots_of_values = #hash{ #lots_of_keys };
Because a list is the result, you use the # sigil even though it is a hash; the values will be the order of the keys specified, including undef values where the specified keys don't exist in the hash.
It sounds like all you're asking is how to access elements of a hash. As Quentin indicates, this is trivially google-able.
The perldata doc covers basic questions, and perlfaq4 covers many other hash questions.
That said, to answer your question:
print $a{'genec'};
print $a{'gened'};
I also would not declare your hash in that way, as it's unclear what is a key and what is a value. Instead, consider:
my %a = ('genea' => 'brain', 'geneb' => 'heart'); # etc.
$GENEC = $a{genec};
$GENED = $a{gened};
Please get yourself a copy of Learning Perl. You'll be glad you did.

Better way to format date in nvarchar [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I need date format like "2011 Oct 24" in SQL 2008 and there is no any inbuilt format in convert function to get this. I got 2 ways to achieve this. Can anybody please guide me which are best way from following 2 ways to get it in terms of execution and performance ?
1) select substring(convert(varchar(20),getdate(),106),8,4) + ' ' +
substring(convert(varchar(20),getdate(),106),4,3) + ' ' +
substring(convert(varchar(20),getdate(),106),1,3)
2) SELECT DATENAME(YYYY,GETDATE()) + ' ' + CAST(DATENAME(MM,GETDATE()) AS VARCHAR(3)) + ' ' + DATENAME(DD,GETDATE())
UPDATE :
Please check below question :
customization on sql datetime format how?
I had also given answer in this question but another answer got more votes than my answer. So I am confused which one is best way.
What is the purpose of this?
If you are passing this to an ASP.NET Web Application, you could keep the date in its raw format and change the format at the application level:
String.Format(Date, "yyyy MMM dd");
However, if you need to format at SQL level, you could do the following:
declare #Date datetime
SET #Date = GETDATE()
SELECT CAST(YEAR(#Date) as nvarchar(4)) + ' ' + SUBSTRING(DATENAME(month, #Date), 0, 4) + ' ' + CAST(DAY(#Date) as nvarchar(2))
http://msdn.microsoft.com/en-us/library/ms187928.aspx

TSQL Concatenation

I often need to concatenate fields in TSQL...
Two issues TSQL forces you to deal with when using the '+' operator are Data Type Precedence and NULL values.
With Data Type Precedence, the problem is conversion errors.
1) SELECT 1 + 'B' = Conversion ERROR
2) SELECT 1 + '1' = 2
3) SELECT '1' + '1' = '11'
In 2), the varchar '1' is implicitly converted to an int, and the math works. However, in 1), the int 1 is NOT implicitly converted to a varchar. This is where DTP is (IMO) getting in the way. Essentially, it favors Math functions over String functions. I Wish :-) that DTP wasn't even a consideration in this case -- why wouldn't the '+' operator be configured so that the operation could favor success over specific data-types? I wouldn't mind if it still favored MATH over String functions when possible -- but why doesn't it favor String functions over Errors? (The only way to be successful in 1) is to treat it as a string function -- so it's not like there's any ambiguity there.) Somebody at Microsoft thought that throwing an error in 1) would be more valuable to the programmer than treating the '+' as a string function. Why? And why didn't they provide a way to override it? (Or did they...that's really the heart of my question.) SET STRING_PREFERENCE ON would have been nice! :-P
In order to deal with this, you have to do more work -- you have to explicitly convert the 1 to a varchar, using any number of different string functions -- typically CAST/CONVERT, but also many others (like LTRIM()) will work.
Conversions become work-intensive when you deal with table fields when you don't know the data-type. This might work:
SELECT 'Fall ' + ' (' + [Term] + ')' -- Output: Fall (2011)
But then again, it might not. It just depends on what data-type of [Term] is. And to complicate that, the dba might change the dataype at some point without telling anyone (because it came as part of a big upgrade package once the vendor finally realized that there are only ever numbers stored in the [Term] field, or whatever reason).
So if you want to be a boyscount, you do this:
SELECT 'Fall ' + ' (' + LTRIM([Term]) + ')'
So now I'm running this LTRIM function every time, even though it might not be necessary, because I don't know the data-type of [Term] (OK -- I can look that up, but that's almost like work, and I don't like interruptions while I'm coding :-P *grump), and also, I don't know that the data-type will never change.
The second issue you have to confront with TSQL concatenation is how to deal with NULL values. For example, this would fail:
SELECT NULL + 'B'
So you need to do this:
SELECT 'Fall ' + ' (' + LTRIM(ISNULL([Term],'')) + ')'
What a pain -- I wish I could just do this:
SELECT 'Fall ' + ' (' + [Term] + ')'
So I'm wondering if there are any (TSQL) ways to avoid having to do explicit data-type conversions and null checks on every field where I have to ensure the '+' operator behaves itself as I need it to.
Thanks!
EDIT
#a1ex07 came up with a great answer for working around the NULL issue (SET CONCAT_NULL_YEILDS_NULL OFF), but as I looked into it, it appears to be problematic as far as forcing stored procedures to re-compile every time they're executed.
SQL Server 2012 does have the CONCAT function which addresses all the issues you raise.
A good summary of the functionality is provided here by SQL Menace
CONCAT takes a variable number of string arguments and concatenates
them into a single string. It requires a minimum of two input values;
otherwise, an error is raised. All arguments are implicitly converted
to string types and then concatenated. Null values are implicitly
converted to an empty string. If all the arguments are null, then an
empty string of type varchar(1) is returned. The implicit conversion
to strings follows the existing rules for data type conversions
UPDATE
You can use CONCAT_NULL_YIELDS_NULL to specify whether NULL + 'txt' results NULL.
Microsft says that CONCAT_NULL_YIELDS_NULL will not work in further versions of SQL Server, but there is still an option to set it through sp_dboption procedure . But probably it's better to use ISNULL as you mentioned in the question.
Try this:
/* 1 */ SELECT cast(1 as varchar) + 'B'; /* = 1B */
/* or */ SELECT convert(varchar, 1) + 'B'; /* = 1B */
/* 2 */ SELECT cast(1 as varchar) + '1'; /* = 11 */
/* 3 */ SELECT '1' + '1'; /* = 11 */
/* or */ SELECT CONVERT(VARCHAR, '1') + CONVERT(VARCHAR, '1');
--NULL value:
DECLARE #A AS VARCHAR(10);
SET #A = NULL;
SELECT ISNULL(#A, '') + 1; /* = 1 */
There is no answer to this for 2005 or 2008. Concatenation without explicit conversions and null checks simply isn't possible.
It looks like the next version of SQL-Server will have a CONCAT function (thanks #Martin) which sounds like exactly what I'm looking for. The downside though is that it will probably be at least a handful of years before my institution decides to upgrade to that version, since they're pretty shy about being early adopters, especially when it comes to Microsoft.
There is a shortcut for the NULL checks right now (CONCAT_NULL_YIELDS_NULL -- thanks #a1ex07), however, using that has a pretty big penalty (re-compiles the procedure every time it is executed), not to mention Microsoft isn't planning to support it in future versions of SQL-Server.