SQL Server

Split function which can be used with 'IN' operator with any character to split, for ex CSV
CREATE FUNCTION [dbo].[Split]

(
  @RowData NVARCHAR(4000)
  , @SplitOn NVARCHAR(5)
)

RETURNS @RtnValue TABLE
(
Id INT IDENTITY(1,1)
, Data NVARCHAR(100)
)
AS
BEGIN
DECLARE @Cnt INT
SET @Cnt = 1
WHILE (CHARINDEX(@SplitOn,@RowData)>0)
BEGIN
INSERT INTO @RtnValue(data)
SELECT
Data = LTRIM(RTRIM(SUBSTRING(@RowData,1,CHARINDEX(@SplitOn,@RowData)-1)))
SET @RowData = SUBSTRING(@RowData,CHARINDEX(@SplitOn,@RowData)+1,LEN(@RowData))
SET @Cnt = @Cnt + 1
END
INSERT INTO @RtnValue (data)
SELECT Data = LTRIM(RTRIM(@RowData))
RETURN
END  

Command to shrink database log file
DBCC SHRINKFILE(, 1)



Important SQL Server basic level Tips
EXISTS Vs DISTINCT: Use EXISTS in place of DISTINCT if you want the result set to
contain distinct values while joining tables. For example: SELECT
DISTINCT d.deptno, d.dname FROM dept d, emp e WHERE d.deptno = e.deptno; The following
SQL statement is a better alternative. SELECT d.deptno, d.dname FROM dept d WHERE
EXISTS (SELECT e.deptno FROM emp e WHERE d.deptno = e.deptno);

Views and it's ADVANTAGES
A view is essentially a named SELECT statement. It acts as a table, but does not contain any data. It relies on the data stored in the underlying table. Like a table, a view can be queried, and data can be inserted, deleted, and modified through a view.

The ENCRYPTION Option
If you want to protect your code, you can encrypt it with the
ENCRYPTION option. The following example creates the view and
encrypts it:
CREATE VIEW vProductInfo
WITH ENCRYPTION
AS SELECT Company, Product, UnitPrice FROM tblSuppliers
INNER JOIN Products
ON Suppliers.SupplierID = Products.SupplierID
When you query its text with the sp_helptext stored procedure, SQL
Server’s answer is: The object comments have been encrypted.

The SCHEMABINDING Option
A View created with the SCHEMABINDING option, the underlying tables cannot be dropped and cannot be altered if it affects the view definition.

CREATE VIEW vwProducts
WITH SCHEMABINDING
AS
SELECT ....

The VIEW_METADATA Option
The VIEW_METADATA option is useful when you use a view through DBLIB
(DB-Library), OLE DB, or ODBC.

The With Check Option Option
The view restricts data access but not data updates and inserts! To avoid this situation, you can use the WITH CHECK OPTION option:
CREATE VIEW viewCustomers
AS SELECT * FROM tblCustomers WHERE statename = 'MD'
WITH CHECK OPTION

No comments:

Post a Comment