"Guy Cohen" <no*****@please.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
1. Select a date in a specific format:
e.g. select FORMAT(recorddate,'DD/MM/YY') from mytable
No doubt there will be people here who will disagree with me here, but in my
experience it's much more efficient to let each layer / tier of your app do
what it's best at.
In this specific case, let your database layer fetch the data, and then use
your presentation layer for formatting that data and displaying it the way
you want. Presumably you're storing your date in SQL Server as either a
datetime or smalldatetime field? Therefore, there's no advantage in
converting it to a varchar just so you can return it to your front end as a
string. If you are binding the data e.g. to a GridView, you can format it
directly in the <asp:GridViewcontrol tag by using the DataFormatString and
HtmlEncode properties of the <asp:BoundFieldcontrol tag e.g.
<asp:GridView ID="MyGridView" runat="server">
<asp:BoundField DataField="MyDateField" HeaderText="Date"
DataFormatString="{0:dd/MM/yy}" HtmlEncode="false" />
</asp:GridView>
If you're simply populating e.g. a TextBox, you can do something like:
MyTextBox.Text = <DataSource>["MyDateField"].ToString("DD/MM/YY");
Just as an aside, you'd be well advised to avoid ambiguous date formats such
as DD/MM/YY - e.g. what would you understand by the date 02/03/04...?
If you use something like "dd MMM yyyy", that would be totally unambiguous
across all cultures.
2. Select only last 4 characters from a string.
e.g. select right(creditcardnumber,4 ) from mytable
That's a little different. Assuming you only ever need to know the last four
digits of the credit card number, then getting the database layer to do this
for you is IMO good practice because it reduces the amount of data sent from
server to client - that's always a "good thing" to do.
Therefore, you need to use SQL Server's SUBSTRING method - look it up in SQL
Server Books On-Line.