Better way to format date in nvarchar [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 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

Related

DB2 and Report Studio: convert string date to numeric

I have a date in this format: Jan 1, 2013 (taken from the date prompt in report studio)
I want to convert it to a timestamp using sql(db2) or a report studio command, the output should look like this: 1130101000000000
Appreciate your inputs.
Regards
Have a look at the VARCHAR_FORMAT() scalar function. I'm honestly not sure what your format there actually is (1 + 2 digit year + 2 digit month + 2 digit day + hours/minutes/second/microseconds ?), but the Info Center page I linked should give you enough information to get what you want. Maybe something like
SELECT VARCHAR_FORMAT(your_date, 'YYMMDDHHMISSFN3')
FROM your_table

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.

SQL Trim after first space [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 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()

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.

Formatting the number in SSRS

I want to format a numeric value to two decimal points (it is an integer variable)
I am using following expression (as used to use in vb6) but it is not working. Please advise how to fix it.
="Total Drawings Rs. " & format(Parameters!TotalDrawings.Value,"###########.00")"
Thanks
Furqan
You use .net format string, not VB6/VBA
= "Total Drawings Rs. " + Format(CDbl(Parameters!TotalDrawings.Value), "##########0.00")
Edit: fixed concat + trailing " + CDbl