.

Saturday, December 13, 2008

SQL String Functions


SQL String Functions



Sql string function is a built-in string function.
It perform an operation on a string input value and return a string or numeric value.
Below is All built-in Sql string function :



Example SQL String Function
-
ASCII
- Returns the ASCII code value of a keyboard button and the rest etc (@,R,9,*) .
Syntax - ASCII ( character)
SELECT ASCII('a') -- Value = 97
SELECT ASCII('b') -- Value = 98
SELECT ASCII('c') -- Value = 99
SELECT ASCII('A') -- Value = 65
SELECT ASCII('B') -- Value = 66
SELECT ASCII('C') -- Value = 67
SELECT ASCII('1') -- Value = 49
SELECT ASCII('2') -- Value = 50
SELECT ASCII('3') -- Value = 51
SELECT ASCII('4') -- Value = 52
SELECT ASCII('5') -- Value = 53



Example SQL String Function - SPACE
-Returns spaces in your SQL query (you can specific the size of space).
Syntax - SPACE ( integer)
SELECT ('SQL') + SPACE(0) + ('TUTORIALS')
-- Value = SQLTUTORIALS
SELECT ('SQL') + SPACE(1) + ('TUTORIALS')
-- Value = SQL TUTORIALS



Example SQL String Function - CHARINDEX
-Returns the starting position of a character string.
Syntax - CHARINDEX ( string1, string2 [ , start_location ] )
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial')

-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 20)

-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 30)
-- Value = 0 (Because the index is count from 30 and above)


Example SQL String Function - REPLACE
-Replaces all occurrences of the string2 in the string1 with string3.
Syntax - REPLACE ( 'string1' , 'string2' , 'string3' )
SELECT REPLACE('All Function' , 'All', 'SQL')
-- Value = SQL Function


Example SQL String Function - QUOTENAME
-Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.
Syntax - QUOTENAME ( 'string' [ , 'quote_character' ] )
SELECT QUOTENAME('Sql[]String')
-- Value = [Sql[]]String]


Example SQL String Function - STUFF
- Deletes a specified length of characters and inserts string at a specified starting index.
Syntax - STUFF ( string1 , startindex , length , string2 )

SELECT STUFF('SqlTutorial', 4, 6, 'Function')
-- Value = SqlFunctional
SELECT STUFF('GoodMorning', 5, 3, 'good')
-- Value = Goodgoodning


Example SQL String Function - LEFT
-Returns left part of a string with the specified number of characters.
Syntax - LEFT ( string , integer)
SELECT LEFT('TravelYourself', 6)
-- Value = Travel
SELECT LEFT('BeautyCentury',6)
-- Value = Beauty


Example SQL String Function - RIGHT
-Returns right part of a string with the specified number of characters.
Syntax - RIGHT( string , integer)
SELECT RIGHT('TravelYourself', 6)
-- Value = urself
SELECT RIGHT('BeautyCentury',6)
-- Value =
Century


Example SQL String Function - REPLICATE
-Repeats string for a specified number of times.

Syntax - REPLICATE (string, integer)
SELECT REPLICATE('Sql', 2)

-- Value = SqlSql


Example SQL String Function - SUBSTRING
-Returns part of a string.

Syntax - SUBSTRING ( string, startindex , length )
SELECT SUBSTRING('SQLServer', 4, 3)

-- Value = Ser


Example SQL String Function - LEN
-Returns number of characters in a string.
Syntax - LEN( string)
SELECT LEN('SQLServer')
-- Value =
9


Example SQL String Function - REVERSE
-Returns reverse a string.
Syntax - REVERSE( string)
SELECT REVERSE('SQLServer')

-- Value = revreSLQS


Example SQL String Function - UNICODE
-Returns Unicode standard integer value.
Syntax - UNICODE( char)
SELECT UNICODE('SqlServer')
-- Value = 83 (it take first character)
SELECT UNICODE('S')
-- Value =
83


Example SQL String Function - LOWER
-Convert string to lowercase.
Syntax - LOWER( string )
SELECT LOWER('SQLServer')

-- Value = sqlserver


Example SQL String Function - UPPER
-Convert string to Uppercase.
Syntax - UPPER( string )
SELECT UPPER('sqlserver')
-- Value = SQLSERVER


Example SQL String Function - LTRIM
-Returns a string after removing leading blanks on Left side.
Syntax - LTRIM( string )
SELECT LTRIM(' sqlserver')
-- Value = 'sqlserver' (Remove left side space or blanks)



Example SQL String Function - RTRIM
-Returns a string after removing leading blanks on Right side.

Syntax - RTRIM( string )
SELECT RTRIM('SqlServer ')
-- Value = 'SqlServer' (Remove right side space or blanks)

SQL Server DataType

SQL Server DataType

All Sql DataType

bigint
Integer data from -2^63 through 2^63-1

binary
Fixed-length binary data with a maximum length of 8,000 bytes

bit

Integer data with either a 1 or 0 value

char
Fixed-length character data with a maximum length of 8,000 characters

datetime

Date and time data from January 1, 1753, through December 31, 9999,with an accuracy of 3.33 milliseconds

decimal

Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1

float
Floating precision number data from -1.79E + 308 through 1.79E + 308

image

Variable-length binary data with a maximum length of 2^31 - 1 bytes

int
Integer data from -2^31 through 2^31 - 1

money
Monetary data values from -2^63 through 2^63 - 1

nchar
Fixed-length Unicode data with a maximum length of 4,000 characters

ntext
Variable-length Unicode data with a maximum length of 2^30 - 1 characters

nvarchar

Variable-length Unicode data with a maximum length of 4,000 characters

numeric

Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1

real
Floating precision number data from -3.40E + 38 through 3.40E + 38

smalldatetime

Date and time data from January 1, 1900, through June 6, 2079,with an accuracy of one minute

smallint

Integer data from -2^15 through 2^15 - 1

smallmoney
Monetary data values from -214,748.3648 through +214,748.3647

sysname

text

Variable-length data with a maximum length of 2^31 - 1 characters

timestamp

tinyint

Integer data from 0 through 255

varbinary
Variable-length binary data with a maximum length of 8,000 bytes

varchar

Variable-length data with a maximum of 8,000 characters

uniqueidentifier

A globally unique identifier

SQL Server Alternate of Count()

SQL Alternative Count

Both SQL Query below returns same result but the speed of retrieving data are different.
Copy Below Both Sql Query to Query analyzer to test it. Customers is a Table Name.

1. SELECT rows FROM sysindexes WHERE id = OBJECT_ID('Customers') AND indid <>
You can use sysindexes system table to get number of ROWS. This column contains the total row count for each table in your database. So, you can use the following select statement instead of Below one:


2. SELECT Count(*) FROM Customers
This SQL query performs full table scan to get the row count.


So, you can improve the speed of the SQL query using the Above First SQL instead of Second SQL Query

What's New in SQL Server 2008?

What's New in SQL Server 2008?

Tuesday December 4, 2007
In a recent interview, SQL Server MVP Brad McGehee offered some observations about Microsoft's pending release of SQL Server 2008. His thoughts, in a nutshell, were:
  • SQL Server continues to get more complex and many DBAs are behind the curve because they haven't yet upgraded to SQL Server 2005
  • PowerShell, included in SQL Server 2008, is unlikely to see much adoption among DBAs
  • The rewritten Reporting Services and Analysis Services are scalable and don't require IIS
  • The Declarative Management Framework (DMF) is the big selling point for 2008, offering consistent enterprise management

Simple Trigger

Simple Trigger

Simple trigger that Delete records from particular table.

Situation : There is one field type is single/joint if user select joint one field enter joint account name and if single then that fields disapears so now if user change joint type to single then joint account name is deleted form database using this trigger.

Answer :

CREATE TRIGGER Tr_Name_UpdateRecordTable
On Table_name
FOR UPDATE,insert AS
declare @Id int
declare @Type int

select @Id=Id from inserted
select @Type=Type from inserted

// @Type=1 mean single else joint

IF @Type=1

BEGIN

Update Table_name set JointAccountFirstName='' ,JointAccountMiddleName='' ,
JointAccountLastName='' where Id=@Id

END

Useful Sql Querys

Useful Sql Querys

Print Row number in Sqlserver 2005

SELECT (ROW_NUMBER() OVER (ORDER BY field_name) )as RowNumber,
field1, field2,fieldn FROM tablename

Get random record from database

SELECT TOP 1 field1, field2,fieldn FROM tablename ORDER BY NEWID()

Find Recenty executed Query in SQLSERVER 2005


SELECT

DMExQryStats.last_execution_time AS [Executed At], DMExSQLTxt.text AS [Query]
FROM
sys.dm_exec_query_stats AS DMExQryStats
CROSS APPLY
sys.dm_exec_sql_text(DMExQryStats.sql_handle) AS DMExSQLTxt
ORDER BY
DMExQryStats.last_execution_time DESC


Taking Multiple backups in SQL SERVER 2005


BACKUP DATABASE Northwind
TO DISK = 'D:\DataabseBkps1\Northwind.bak'
MIRROR
TO DISK = 'E:\DataabseBkps2\Northwind.bak'
WITH FORMAT;
  • consistent enterprise management

SQL Server Combine 2 Different Table

SQL Server : Combine 2 Different Table

This SQL is use to combine 2 different table together for other purpose.
SELECT ISNULL(a.Col1,b.Cola) , ISNULL(a.Col2,b.Colb)
FROM Table1 a
FULL JOIN Table2 b
ON a.Col1 = b.Cola

Here is 2 Different Table,
Table Name : Salary
NameSalary
emil1000
rayden2000


Table Name: Flight
FligtTicketPrice
Kuala Lumpur265
Bangkok878


Below Sql is use to combine above 2 Tables Become below 1 Table
SELECT ISNULL(a.Name,b.FlightTicket) AS Col1, ISNULL(a.Salary,b.Price) AS Col2 FROM Salary a
FULL JOIN Flight b ON a.Name = b.FlightTicket

Col1Col2
emil1000
rayden2000
Kuala Lumpur265
Bangkok878

SQL DATE Function

SQL DATENAME Function

It return specifies the part of the date name and the DATENAME for Date Time such as Year, Quarter, Month, Day, Hour, Minute and Milisecond.

SQL DATENAME Syntax
DATENAME ( datepart , date )

Example

SELECT GETDATE() = 2007-05-30 23:13:38.763

SELECT DATENAME(year, GETDATE())
SELECT DATENAME(yy, GETDATE())
SELECT DATENAME(yy, GETDATE())
- It will return value = 2007

SELECT DATENAME(quarter, GETDATE())
SELECT DATENAME(qq, GETDATE())
SELECT DATENAME(q, GETDATE())
-It will return value = 2 (because 1 quarter equal to 3 month,Detail see below table)

Month

Quarter Value

January - March

1

April - June

2

July - September

3

October - December

4





SELECT DATENAME(month, GETDATE())
SELECT DATENAME(mm, GETDATE())
SELECT DATENAME(m, GETDATE())
- It will return value = May

SELECT DATENAME(dayofyear, GETDATE())
SELECT DATENAME(dy, GETDATE())
SELECT DATENAME(y, GETDATE())
- It will return value = 150 (this is calculate total day from 1 jan 2007 until 30 may 2007)

SELECT DATENAME(day, GETDATE())
SELECT DATENAME(dd, GETDATE())
SELECT DATENAME(d, GETDATE())
- It will return value =
30

SELECT DATENAME(week, GETDATE())
SELECT DATENAME(wk, GETDATE())
SELECT DATENAME(ww, GETDATE())
- It will return value = 23 (this is 23rd week from 1 jan 2007)

SELECT DATENAME(hour, GETDATE())
SELECT DATENAME(hh, GETDATE())
- It will return value = 23 (time for 24 hour)

SELECT DATENAME(minute, GETDATE())
SELECT DATENAME(mi, GETDATE())
SELECT DATENAME(n, GETDATE())
- It will return value = 13 (minute)

SELECT DATENAME(second , GETDATE())
SELECT DATENAME(ss, GETDATE())
SELECT DATENAME(s, GETDATE())
- It will return value = 38 (second)

SELECT DATENAME(millisecond , GETDATE())
SELECT DATENAME(ms, GETDATE())
- It will return value = 763 (milisecond)

Naming Conventions

Control Naming Conventions

BackgroundWorker - bgwrk
BindingNavigator - bndnav
BindingSource - bndsrc
Button - btn
CheckBox - chk
CheckedListBox - chklb
ColorDialog - clrdlg
ComboBox - cmb
ContextMenuStrip - cms
DataGridView - grd (I don’t differentiate between variants)
DataSet - ds
DateTimePicker - dtpick
DirectoryEntry - dirent
DirectorySearcher - dirsrc
DomainUpDown - dupdn
ErrorProvider - err
EventLog - evtlog
FileSystemWatcher - fsw
FlowLayoutPanel - pnl (I don’t differentiate between variants)
FolderBrowserDialog - flddlg
FontDialog - fntdlg
GroupBox - grp
HelpProvider - hlp
HScrollBar - hscr
ImageList - imglst
Label - lbl
LinkLabel - lnklbl
ListBox - lb
ListView - lvw
MaskedTextBox - txt (I don’t differentiate between variants)
MenuStrip - mnustrp
MessageQueue - mq
MonthCalendar - cal
NotifyIcon - noticn
NumericUpDown - nupdn
OpenFileDialog - opndlg
PageSetupDialog - pgdlg
Panel - pnl (I don’t differentiate between variants)
PerformanceCounter - prfcnt
PictureBox - pic
PrintDialog - prndlg
PrintDocument - prndoc
PrintPreviewControl - ppc
PrintPreviewDialog - ppd
Process - proc
ProgressBar - prg
PropertyGrid - prpgrd
RadioButton - btn
RichTextBox - txt
SaveFileDialog - savdlg
SerialPort - prt
ServiceController - svcctr
SplitContainer - cntr
Splitter - splt
StatusStrip - stat
TabControl - tabctl
TableLayoutPanel - pnl (I don’t differentiate between variants)
TextBox - txt
Timer - tmr
ToolStrip - tstrp
ToolStripContainer - tstrpctr
ToolStripMenuItem - mnu
ToolTip - tip
TrackBar - tbar
TreeView - tvw
VScrollBar - vscr
WebBrowser - web
ReportViewer - rpt

.