This page contains a collection of the freqently asked questions about SQL Server in the various SQL Server newsgroups interlaced with some, from my own experience with the product over the years.
Return a list of executable files in the current directory ?.
Is there a way to find duplicate records in a table by: Firstname, Lastname, Email?
EXTRACT Numeric characters from a string
Function to capitalize the first
letter
How to use the MIN() and MAX() Functions with the OR Keyword to Find Target Rows
How to add text string to a text data type
Pad leading zereos to a string?
How to convert a string in d/m/y format to datetime
How to calculate last day of the month
Get the name of the month from an Int value
Use TOP to select the records from row 8 to 13
Use SET method to select the nth records from a table
Sort a column that contains email addresses by "domain"
How to quickly create a table using existing table
How to schedule the scripting of database objects?
Different ways to load data from text files to SQL Server(DTS, bcp,Bulk Insert, ODBC)
How many instances of SQL Server can be created?
EXEC master..xp_cmdshell 'dir *.exe'
Select Firstname , Lastname ,Email, count (*)
group by
Firstname , Lastname ,Email
having
count (*) > 1
OR
select *
from table t
where 1 < (select count(*) from table t1 where t1.field1 = t.field1 and
t1.field2 = t.field2 etc)
Select len('123' + ' ') returns 3? But it should have returned 8 (3 + 5 spaces). So how to count the last 5 spaces?
We need to use DATALENGTH() instead, because LEN ignores trailing spaces.
SELECT DATALENGTH('123' + ' ')
declare @str varchar(30)
select @str = 'MyString19796Character'
select substring(@str, patindex('%[1-9]%', @str), 5)
northwind.dbo.employees
========================
create function INITCAP(@par
varchar(8000))
returns varchar(8000)
AS
BEGIN
declare @counter as int
declare @lastchar as
varchar(1)
set @lastchar=' '
begin
if @lastchar=' '
begin
set @par= STUFF(@par, @counter, 1,
upper(substring(@par,@counter,1)))
set @lastchar=substring(@par,@counter,1)
set @counter=@counter+1
end
else
begin
select @par= STUFF(@par, @counter, 1, lower(substring(@par,@counter,1)))
set @lastchar=substring(@par,@counter,1)
set @counter=@counter+1
end
return @par
END
Go
SET @TargetOrder = 10330
OrderId
FROM
Orders
WHERE
OrderId = @TargetOrder
OR OrderId = (SELECT MAX(OrderId) FROM orders
WHERE OrderId < @TargetOrder)
OR OrderId = (SELECT MIN(OrderId) FROM orders
WHERE OrderId > @TargetOrder)
TOP 3
*
FROM
orders
WHERE
OrderId >= (SELECT MAX(OrderId) FROM orders WHERE OrderId
< @TargetOrder)
ORDER BY
OrderId
If you want to convert 28/01/03 to a datetime value. then use SET DATEFORMAT dmy
SET DATEFORMAT dmy
go
declare @zzzdate as datetime
set @zzzdate = '28/01/03'
select convert(datetime, @zzzdate, 103)
where nameid not in (select top 7 nameid from #dups b)
To find the 10th row: ------------------------------------------------------------ SELECT * FROM pubs..Titles a WHERE 10 = (SELECT count(*) from pubs..Titles b Where b.title_id <= a.title_id) ORDER BY title_id OR SELECT TOP 1 * FROM pubs..Titles a WHERE title_id NOT IN (SELECT TOP 9 title_id FROM pubs..Titles b order by title_id ) order by title_id OR DECLARE @row_number INTEGER SET @row_number = 10 SELECT * FROM pubs..Titles AS T WHERE (SELECT COUNT(*) FROM pubs..Titles WHERE title_id <= T.title_id) = @row_number
Email char(256) NOT NULL
)
GO
INSERT INTO #Test SELECT 'Ad@george.com'
INSERT INTO #Test SELECT 'b@george.com'
INSERT INTO #Test SELECT 'c@bc.com'
INSERT INTO #Test SELECT 'd@abc.com'
d@abc.com
c@bc.com
Ad@george.com
b@george.com
order by substring(email, charindex('@', email),len(email) )
FROM #Test
ORDER BY STUFF(Email, 1, PATINDEX('%@%', Email), SPACE(0))
FROM YourTable
ORDER BY ISNULL(Type, (SELECT MAX(Type) + 1 FROM YourTable))
SELECT * FROM #fooBarsAreGoodChocolateBars fb,
#someOtherRidiculousTableName so
WHERE fb.something = so.something
AND fb.id = 5
AND so.category = 'bears'
Use SELECT * INTO T2 FROM T1
The SELECT INTO statement creates a table with the same schema and copies the data into it.
Constraints and indexes are not copied, though. IDENTITY property is. The above example will also copy all of the records from the old table into the new table... If you merely wish the table and no data , use a false where clause ie where 0 = 1 or use top 0 *
CONVERT
(
CHAR(8),
DATEADD(MONTH, 1, GETDATE()-DAY(GETDATE())+1)-1,
112
)
(
playerid int NOT NULL primary key,
points int NOT NULL
)
go
insert into #James values (5, 5)
insert into #James values (6, 12)
insert into #James values (8, 7)
insert into #James values (9, 11)
(select count(*)
from #James as j2
where j2.points <= j1.points) as rank
from #James as j1
order by rank
We can use the script method of SQL-DMO...here is a sample....
Dim oSS As SQLDMO.SQLServer
Dim oDb As SQLDMO.Database
Dim oT As SQLDMO.Transfer
Dim sS As String
Sub Script()
Set oSS = New SQLDMO.SQLServer
Set oT = New SQLDMO.Transfer
oSS.Connect "server", "user", "password" 'Connect to the server
Set oDb = oSS.Databases("pubs") 'Use a DB
oT.CopyAllTables = True
oDb.ScriptTransfer oT, SQLDMOXfrFile_SingleFile, "C:\pubs.sql"
End Sub
More information about SQL-DMO at: Sql-Dmo
If its a SQL2000 ,we can also use SCPTXFR.exe utility in the upgrade folder to script things out.
The usage is explained in:
DTS Does Not Copy Identity, Indexes, Primary Key or Other Constraints (Q220163)
SQL Server provides several solutions for importing and exporting text files. Data transformation services (DTS) supports text as a data source or destination; the bcp and osql utilities can import and export text files; and T-SQL provides BULK INSERT for importing text. Another solution is less widely known: the Jet text file driver can connect SQL Server directly to text files via a linked server. This ODBC driver handles some tasks better than any of the other solutions, and it provides pure T-SQL solutions to many problems. For more click here
Another way is to use OPENROWSET like
exec master..xp_cmdshell 'echo "this is a test" >> c:\temp\test.txt & echo
"this is a test2" >> c:\temp\test.txt'
go
create view v_
as
select *
from OpenRowset('Microsoft.Jet.OLEDB.4.0',
'Text;Database=c:\temp\;HDR=NO',
'select * from test.txt')
go
select * from v_
go
drop view v_
, @column = 'newcol'
, @typetext = 'INT'
, @publication_to_add = '<name of publication authors is
included in>'
Databases per Instance 32,767
FileGroups per database 256
Files per database 32,767
Database size 1,048,516
TB
Data File size 32
TB
Log File size 32
TB
Total Database objects 2,147,483,647
Columns per table 1,024