Labels

admin (1) aix (1) alert (1) always-on (2) Architecture (1) aws (3) Azure (1) backup (3) BI-DWH (10) Binary (3) Boolean (1) C# (1) cache (1) casting (3) cdc (1) certificate (1) checks (1) cloud (3) cluster (1) cmd (7) collation (1) columns (1) compilation (1) configurations (7) Connection-String (2) connections (6) constraint (6) copypaste (2) cpu (2) csv (3) CTE (1) data-types (1) datetime (23) db (547) DB2 (1) deadlock (2) Denali (7) device (6) dotNet (5) dynamicSQL (11) email (5) encoding (1) encryption (4) errors (124) excel (1) ExecutionPlan (10) extended events (1) files (7) FIPS (1) foreign key (1) fragmentation (1) functions (1) GCP (2) gMSA (2) google (2) HADR (1) hashing (3) in-memory (1) index (3) indexedViews (2) insert (3) install (10) IO (1) isql (6) javascript (1) jobs (11) join (2) LDAP (2) LinkedServers (8) Linux (15) log (6) login (1) maintenance (3) mariadb (1) memory (4) merge (3) monitoring (4) MSA (2) mssql (444) mssql2005 (5) mssql2008R2 (20) mssql2012 (2) mysql (36) MySQL Shell (5) network (1) NoSQL (1) null (2) numeric (9) object-oriented (1) offline (1) openssl (1) Operating System (4) oracle (7) ORDBMS (1) ordering (2) Outer Apply (1) Outlook (1) page (1) parameters (2) partition (1) password (1) Performance (103) permissions (10) pivot (3) PLE (1) port (4) PostgreSQL (14) profiler (1) RDS (3) read (1) Replication (12) restore (4) root (1) RPO (1) RTO (1) SAP ASE (48) SAP RS (20) SCC (4) scema (1) script (8) security (10) segment (1) server (1) service broker (2) services (4) settings (75) SQL (74) SSAS (1) SSIS (19) SSL (8) SSMS (4) SSRS (6) storage (1) String (35) sybase (57) telnet (2) tempdb (1) Theory (2) tips (120) tools (3) training (1) transaction (6) trigger (2) Tuple (2) TVP (1) unix (8) users (3) vb.net (4) versioning (1) windows (14) xml (10) XSD (1) zip (1)

PIVOT

PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output.


SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, 
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost 
    FROM Production.Product) SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) PivotTable

Notes:
  • Available from SQL Server 2005.
  • When aggregate functions are used with PIVOT, the presence of any null values in the value column are not considered when computing an aggregation.
  • Pivot columns are specific values from the column of the source table, and can't be declared dynamic.

JOIN deletion to table that not in the join

DELETE dbo.TableA
FROM dbo.ViewOnTableA a
JOIN dbo.TableB b ON a.ID = b.ID
--> all the rows of dbo.TableA will be deleted!

The deleted table must be in the joins, Otherwise all the rows of the table will be deleted.

The statement above should be written:
DELETE dbo.TableA
FROM dbo.ViewOnTableA a
JOIN dbo.TableA ta ON a.ID = ta.ID
JOIN dbo.TableB b ON a.ID = b.ID

Unique columns to not NULL values

New in SQL SERVER 2008:
We can define an unique column, that NULL is not need to be unique, or in other words: the unique check is only for not NULL values.

CREATE UNIQUE NONCLUSTERED INDEX IX_TableName_UniqueColumn
ON dbo.TableName (UniqueColumn)
WHERE UniqueColumn IS NOT NULL
GO
 SELECT ID, UniqueColumn FROM TableName WHERE ID in (5, 6, 7)
-- for the example. lets say that the results are: 5, NULL ; 6, NULL ; 7, NULL.
UPDATE TableName SET UniqueColumn = 'test' WHERE ID = 5 --will be success
UPDATE TableName SET UniqueColumn = 'test' WHERE ID = 6 --will be failed
UPDATE TableName SET UniqueColumn = NULL WHERE ID = 5 --will be success

smalldatetime

smalldatetime defines a date that is combined with a time of day. The time is based on a 24-hour day, with seconds always zero (:00) and without fractional seconds.
If the seconds are 29.998 or less it rounds down to the nearest minute. If the seconds are 29.999 or more rounds up to the next minute.




Default values to SQL function parameters

Unlike stored procedure parameters, When a parameter of the function has a default value, the keyword 'DEFAULT' must be specified when calling the function in order to get the default value. 

CREATE FUNCTION [dbo].[FUNCTIONNAME] (
@P1 int, 
@P2 int =0 
)........

select * from dbo.FUNCTIONNAME(1)
Result: an error message:
An insufficient number of arguments were supplied for the procedure or function dbo.FUNCTIONNAME.

Solution: 
We have to use the 'DEFAULT' keyword:
Select * from dbo.FUNCTIONNAME(1, DEFAULT)

If the 2 parameters have default, 
CREATE FUNCTION [dbo].[FUNCTIONNAME] (
@P1 int =0, 
@P2 int =0 
)........
we have to use 'DEFAULT' twice:
Select * from dbo.FUNCTIONNAME(DEFAULT, DEFAULT)

CASE without Else expression

The Case expression syntax is:
CASE ..... WHEN ....... THEN ........ [ ...more WHEN ... THEN expressions ] 
     [ ELSE ......... ]  END 
ELSE is not obligatory expression.
And - If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL.
CASE without the Else expression can cause to insertion of NULL values!


For Example:
DECLARE @TestTable (TestColumn int not null)
INSERT INTO @TestTable select 1 union select 2 union select 3
-- case without else expression
UPDATE@TestTable 
SET TestColumn = ( CASE WHEN TestColumn = 2 THEN 22 END )
-- Result: table values are: NULL, 22, NULL
-- if we want to update only the '2' rows:
UPDATE@TestTable 
SET TestColumn = ( CASE WHEN TestColumn = 2 THEN 22 ELSE TestColumn END )
-- Result: table values are: 1, 22, 3




Linked server

-- get exists linked servers:
select * from sys.servers

-- add new linked server:
exec sp_addlinkedserver 
@server='Dev2008ItaiTest', -- the name of the linked server
@srvproduct= '', -- the product name of the OLE DB data source
@provider='SQLNCLI', -- the unique programmatic identifier (PROGID) of the OLE DB provider that corresponds to this data source
@datasrc='DEV2008', -- server name
@location='', -- the location of the database as interpreted by the OLE DB provider
@provstr='Query Timeout=10' -- another parameters.

Notes:
  • If the product name of the linked server is SQL Server, provider_name, data_source, location, provider_string, and catalog do not have to be specified.
  • Return Values: 0 for success or 1 for failure.

-- use linked server:
select * from Dev2008ItaiTest.DBName.dbo.ObjectName

-- delete linked server:
sp_dropserver @server='Dev2008ItaiTest'

Check if an expression is numeric

IsNumeric:
select IsNumeric('0.2') -- return 1
select IsNumeric('asasa') -- return 0

http://msdn.microsoft.com/en-us/library/aa933213(v=sql.80).aspx

Note: parameter with value of NULL is not considered numeric, but parameter with value of empty string ('') will be converted to zero:

DECLARE @P int
SET @P = NULL
SELECT IsNumeric(@P) -- return 0
SET @P = ''
SELECT IsNumeric(@P) -- return 1
SELECT IsNumeric(NULL) -- return 0
SELECT IsNumeric('') -- return 0

Line break in a SQL Server string

In order to insert a line break in a SQL Server string, use CHAR(13) or CHAR(10):

CHAR(13) - carriage return:
print 'line 1' + CHAR(13) + 'line 2'

CHAR(10) - Line feed:
print 'line 1' + CHAR(10) + 'line 2'

Note: if you select those string to grid, it won't be showen as 2 lines, but the values of CHAR(13)/CHAR(10) will be saved.

SET PARSEONLY

SET PARSEONLY { ON | OFF }

When SET PARSEONLY is ON, SQL Server only parses the statement. 
When SET PARSEONLY is OFF, SQL Server compiles and executes the statement.

The setting of SET PARSEONLY is set at parse time and not at execute or run time.

SET FMTONLY

SET FMTONLY { ON | OFF }

SET FMTONLY returns only metadata to the client. 
For 'regular' tables - the result set only have headers of the results but no data.
SET FMTONLY can be used to test the format of the response without actually running the query.

SET FMTONLY ON
GO
-- no rows will be return (only the headers):
SELECT * FROM [dbo].[StamTable2]
GO
SET FMTONLY OFF
GO
-- all the rows will be return:
SELECT * FROM [dbo].[StamTable2]
GO


What is metadata?
The short definition is that it’s data about data.
Metadata is used to add context and understanding about data that users are accessing, or to hide complexity from end users who aren’t required to know or understand the technical details of data.
(from MSDN SQL Server Metadata Toolkit: http://archive.msdn.microsoft.com/SqlServerMetadata)

See an article about Using SQL Server meta data to list tables that make up views:
http://www.mssqltips.com/tip.asp?tip=1638

SQL Server Denali introduces new metadata discovery capabilities, removing the need to use the older SET FMTONLY option:
http://www.sqlmag.com/blogs/puzzled-by-t-sql/entryid/76283/denali-t-sql-at-a-glance-metadata-discovery

OPENQUERY

OPENQUERY:
Executes the specified pass-through query on the specified linked server.
OPENQUERY ( linked_server ,'query' )

OPENQUERY can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement.

http://msdn.microsoft.com/en-us/library/ms188427.aspx

OPENQUERY can be a target of select query, like:
SELECT ..... FROM OPENQUERY ( linked_server ,'query' )

SQL Azure

SQL Azure is a cloud-based service from Microsoft offering data storage capabilities.

Useful links:

SQL Azure - microsoft site:

SQL Azure Labs:

Unsupported Transact-SQL Statements in SQL Azure:

Connect to SQL Azure through a special project for developers without SSMS, Houston project:

INSTEAD OF DELETE trigger on view - ERROR

Error message:
DELETE is not allowed because the statement updates view "VVV" which participates in a join and has an INSTEAD OF DELETE trigger.

Explanation:
A view with an INSTEAD OF UPDATE / INSTEAD OF DELETE trigger cannot be a target of an UPDATE or DELETE statements with a FROM clause.

Work-Arounds:
1. Replace the JOIN with 'IN':
delete dbo.test1 
from dbo.test1 t1 join dbo.test2 t2 on t1.Id = t2.Id
-->
delete dbo.test1 where t1.Id IN (select Id from dbo.test2)

2. Replace the JOIN with EXISTS:
delete dbo.test1
from dbo.test1 t1 join dbo.test2 t2 on t1.Id = t2.Id
-->
delete dbo.test1
from dbo.test1 t1
where exists ( Select top 1 Id from dbo.test2 t2 Where t1.Id = t2.Id )

3. If possible - do the update/deletion on the original tables (= the source table/tables of the View).

SSRS - Expression-based Connection Strings

="data source=" & Parameters!ServerName.Value & ";initial catalog=AdventureWorks

Specify connection strings parameters as a report parameter.
Expression-based connection strings are evaluated at run time.

SQL Server code name Denali Home page

SQL Server code name Denali Home page:

Return value of stored procedure

DECLARE @return_value int
EXEC   @return_value = [dbo].[SP_NAME]  @ID = 131279, ......
SELECT 'Return Value' = @return_value

  • When the SP is successful, @return_value would be 0.
  • Also @return_value=NULL means an error.

If we want to return an output value from the SP, we have to declare an output parameter in the SP declaration:
CREATE PROCEDURE [dbo].[SP_NAME]
@Param1 int,
....... ,
@SpCount INT OUTPUT
AS
.......
and insert it a value in the SP code.
When execute SP:
DECLARE @Count int
EXEC   @return_value = [dbo].[SP_NAME]  @ID = 131279, ......, 
              @SpCount = @Count OUTPUT

Pattern Matching in the LIKE operator

% - Any string of zero or more characters.
_ - Any single character.
[ ] - Any single character within the specified range ([a-f]) or set ([abcdef]).
[^] - Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
[[] - specific speicial character - in this case '['.


Find and kill active connections to Database

select DB_NAME(dbid), ('kill ' + convert(nvarchar(10), spid) ) as kill_statement, * 
from sys.sysprocesses where DB_NAME(dbid) = 'DBNAME'
--or:

DECLARE @SQL nvarchar(max) 
SELECT @SQL=COALESCE(@SQL,'') +'Kill '+CAST(spid AS nvarchar(10))+ '; '  
FROM sys.sysprocesses WHERE DB_NAME(dbid) = 'DBNAME'