Category Archives: Transact-SQL

Databases SQL Server Tips & tricks Transact-SQL

How to get different SQL Server date formats

Below is a list of formats and an example of the output.  The date used for all of these examples is “2006-12-30 00:38:54.840”.

DATE ONLY FORMATS
Format # Query Sample
1 select convert(varchar, getdate(), 1) 12/30/06
2 select convert(varchar, getdate(), 2) 06.12.30
3 select convert(varchar, getdate(), 3) 30/12/06
4 select convert(varchar, getdate(), 4) 30.12.06
5 select convert(varchar, getdate(), 5) 30-12-06
6 select convert(varchar, getdate(), 6) 30 Dec 06
7 select convert(varchar, getdate(), 7) Dec 30, 06
10 select convert(varchar, getdate(), 10) 12-30-06
11 select convert(varchar, getdate(), 11) 06/12/30
12 select convert(varchar, getdate(), 12) 061230
23 select convert(varchar, getdate(), 23) 2006-12-30
101 select convert(varchar, getdate(), 101) 12/30/2006
102 select convert(varchar, getdate(), 102) 2006.12.30
103 select convert(varchar, getdate(), 103) 30/12/2006
104 select convert(varchar, getdate(), 104) 30.12.2006
105 select convert(varchar, getdate(), 105) 30-12-2006
106 select convert(varchar, getdate(), 106) 30 Dec 2006
107 select convert(varchar, getdate(), 107) Dec 30, 2006
110 select convert(varchar, getdate(), 110) 12-30-2006
111 select convert(varchar, getdate(), 111) 2006/12/30
112 select convert(varchar, getdate(), 112) 20061230
TIME ONLY FORMATS
8 select convert(varchar, getdate(), 8) 00:38:54
14 select convert(varchar, getdate(), 14) 00:38:54:840
24 select convert(varchar, getdate(), 24) 00:38:54
108 select convert(varchar, getdate(), 108) 00:38:54
114 select convert(varchar, getdate(), 114) 00:38:54:840
DATE & TIME FORMATS
0 select convert(varchar, getdate(), 0) Dec 12 2006 12:38AM
9 select convert(varchar, getdate(), 9) Dec 30 2006 12:38:54:840AM
13 select convert(varchar, getdate(), 13) 30 Dec 2006 00:38:54:840AM
20 select convert(varchar, getdate(), 20) 2006-12-30 00:38:54
21 select convert(varchar, getdate(), 21) 2006-12-30 00:38:54.840
22 select convert(varchar, getdate(), 22) 12/30/06 12:38:54 AM
25 select convert(varchar, getdate(), 25) 2006-12-30 00:38:54.840
100 select convert(varchar, getdate(), 100) Dec 30 2006 12:38AM
109 select convert(varchar, getdate(), 109) Dec 30 2006 12:38:54:840AM
113 select convert(varchar, getdate(), 113) 30 Dec 2006 00:38:54:840
120 select convert(varchar, getdate(), 120) 2006-12-30 00:38:54
121 select convert(varchar, getdate(), 121) 2006-12-30 00:38:54.840
126 select convert(varchar, getdate(), 126) 2006-12-30T00:38:54.840
127 select convert(varchar, getdate(), 127) 2006-12-30T00:38:54.840
FORMATS WITH ISSUES
130 select convert(varchar, getdate(), 130) 10 ?? ????? 1427 12:38:54:840A
131 select convert(varchar, getdate(), 131) 10/12/1427 12:38:54:840AM

You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample statement Output
select replace(convert(varchar, getdate(),101),’/’,”) 12302006
select replace(convert(varchar, getdate(),101),’/’,”) + replace(convert(varchar, getdate(),108),’:’,”) 12302006004426

read more »

Code Snippets SQL Server Transact-SQL

DBCC SHRINKFILE (Transact-SQL)

A. Shrinking a data file to a specified target size

The following example shrinks the size of a data file named DataFile1 in the UserDB user database to 7 MB.


USE UserDB;
GO
DBCC SHRINKFILE (DataFile1, 7);
GO

B. Shrinking a log file to a specified target size

The following example shrinks the log file in the AdventureWorks database to 1 MB. To allow the DBCC SHRINKFILE command to shrink the file, the file is first truncated by setting the database recovery model to SIMPLE.


USE AdventureWorks2012;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2012
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2012_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2012
SET RECOVERY FULL;
GO

C. Truncating a data file

The following example truncates the primary data file in the AdventureWorks database. The sys.database_files catalog view is queried to obtain the file_id of the data file.


 

USE AdventureWorks2012;
GO
SELECT file_id, name
FROM sys.database_files;
GO
DBCC SHRINKFILE (1, TRUNCATEONLY);

D. Emptying a file

The following example demonstrates the procedure for emptying a file so that it can be removed from the database. For the purposes of this example, a data file is first created and it is assumed that the file contains data.


USE AdventureWorks2012;
GO
-- Create a data file and assume it contains data.
ALTER DATABASE AdventureWorks2012
ADD FILE (
NAME = Test1data,
FILENAME = 'C:\t1data.ndf',
SIZE = 5MB
);
GO
-- Empty the data file.
DBCC SHRINKFILE (Test1data, EMPTYFILE);
GO
-- Remove the data file from the database.
ALTER DATABASE AdventureWorks2012
REMOVE FILE Test1data;
GO

https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-shrinkfile-transact-sql

SQL Server Transact-SQL

SQL SERVER – FIX : Error 15023: User already exists in current database.

Error 15023: User already exists in current database.

1) This is the best Solution.

First of all run following T-SQL Query in Query Analyzer. This will return all the existing users in database in result pan.

USE YourDB
GO
EXEC sp_change_users_login 'Report'
GO

Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist. In following example ‘ColdFusion’ is UserName, ‘cf’ is Password. Auto-Fix links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins.

USE YourDB
GO
EXEC sp_change_users_login 'Auto_Fix', 'ColdFusion', NULL, 'cf'
GO

Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Update_One’ links the specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specified

USE YourDB
GO
EXEC sp_change_users_login 'update_one', 'ColdFusion', 'ColdFusion'
GO

more details in http://blog.sqlauthority.com/2007/02/15/sql-server-fix-error-15023-user-already-exists-in-current-database/

SQL SQL Server Transact-SQL

Recursive Queries using Common Table Expressions (CTE) in SQL Server

Given the example , hierarchical data structures, organizational charts and other parent-child table relationship reports can easily benefit from the use of recursive CTEs. Common Table Expression is just one of those T-SQL enhancements available for SQL Server 2005. CTEs bring us the chance to create much more complex queries while retaining a much simpler syntax. They also can lessen the administrative burden of creating and testing views for situations where the view will not be reused.

Syntax

WITH cte_alias (column_aliases)
AS
(
cte_query_definition   --initialization
UNION ALL
cte_query_definition2 --recursive execution
)
SELECT * FROM cte_alias

Sample (from Root nodes to Leaf  noes)

WITH Managers AS
(
--initialization
SELECT EmployeeID, LastName, ReportsTo
FROM Employees
WHERE ReportsTo IS NULL
UNION ALL
--recursive execution
SELECT e.employeeID,e.LastName, e.ReportsTo
FROM Employees e INNER JOIN Managers m
ON e.ReportsTo = m.employeeID
)
SELECT * FROM Managers

Sample (From Leaf nodes to Root nodes), where u must specifie the leaves to include/use.

WITH xEmployees AS
(
--initialization
SELECT  EmployeeID, LastName, ReportsTo
FROM Employees
WHERE EmployeeID IN (55,98,65,12)  -- sample Leaf nodes to filter/use
UNION ALL
--recursive execution
SELECT a.EmployeeID,a.LastName,a.ReportsTo
FROM Employees a INNER JOIN xEmployees m
ON a.EmployeeID = m.reportsTo
)
SELECT Distinct EmployeeID, LastName, ReportsTo  FROM xEmployees

!Importante to use “Distinct” statement!

SQL Server Transact-SQL

get a substring in SQL SERVER using space as separator

get a substring in SQL SERVER using space as separator


SELECT CASE CHARINDEX(' ', news.description, 40)
  WHEN 0 THEN news.description
  ELSE SUBSTRING(news.description, 0, CHARINDEX(' ', news.description, 40) - 0)
  END
 AS FirstWord
FROM news

source:
http://www.dreamincode.net/forums/topic/239440-how-can-i-get-a-substring-in-sql-server-using-space-as-separator/
CHARINDEX (Transact-SQL) http://msdn.microsoft.com/pt-pt/library/ms186323.aspx

SUBSTRING (Transact-SQL)http://msdn.microsoft.com/en-us/library/ms187748.aspx

SQL Server Transact-SQL

SQL Server Dumper

SQL Server Dumper enables you to dump selected SQL Server database tables into SQL INSERT statements, that are saved as local .sql files and contain all the data required to create a duplicate table, or to be used for backup purposes. You can choose to create an individual .sql file for each table, or combine all selected tables into a single file.

This program implements the following special features:

  • Foreign Keys> order tables in text file in order to insert data without colisions/errors
  • Primary Key IDENTITY> guarantees the value of the IDENTITY field
  • Reference to itself> eliminates the constraint and at the end create it again

http://sqldumper.ruizata.com/

Microsoft SQL Server Transact-SQL

SQL SERVER – Insert Data From One Table to Another Table

INSERT INTO SELECT – SELECT INTO TABLE

Following three questions are many time asked on this blog.

How to insert data from one table to another table efficiently?
How to insert data from one table using where condition to anther table?
How can I stop using cursor to move data from one table to another table?

There are two different ways to implement inserting data from one table to another table. I strongly suggest to use either of the method over cursor. Performance of following two methods is far superior over cursor. I prefer to use Method 1 always as I works in all the case.

read more »

Microsoft SQL Server Tips & tricks Transact-SQL

SQL to Select a random row from a database table

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

source link: http://www.petefreitag.com/item/466.cfm
Microsoft SQL Server Transact-SQL

Insert Multiple Rows in SQL Server

In SQL Server 2005, in order to insert 3 rows to a table, you had to run 3 INSERT statements:

insert into Customers (Name, City, Phone) values (‘Customer #1’, ‘Jerusalem’, ‘2343245’)

insert into Customers (Name, City, Phone) values (‘Customer #2’, ‘Tel Aviv’, ‘0987345’)

insert into Customers (Name, City, Phone) values (‘Customer #3’, ‘Haifa’, ‘275466’)

In SQL Server 2008, you can insert multiple rows in a single insert statement that takes a number of value arrays:

insert into Customers (Name, City, Phone)

values

(‘Customer #1’, ‘Jerusalem’, ‘2343245’),

(‘Customer #2’, ‘Tel Aviv’, ‘0987345’),

(‘Customer #3’, ‘Haifa’, ‘275466’)

Source link

SQL Server Transact-SQL

SQL collations

Query:

select * from fn_helpcollations()
where name like ‘%SQL_Latin1_General_CP1_CI_AS%’
or name = ‘Latin1_General_CI_AS’
or name like ‘%cp1%’

Query result:

read more »