Open closed document in MS SQL SERVER



We can retrieve the query even we closed our query window in SQL without saving the script.

SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script] FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC

Above query provides a list of scripts and its time of execution in the last 24 hours. 

This will be work for all executed scripts not only a view or procedure.

isNAN function in javascript

isNAN function checks the argument and returns true if the argument is not a number else return false


Example of isNAN()

var val='04cs';

if(isNAN(val))
{
alert('this is not a number') ;
}else{
alert('this is a number') 

}


ANS : this is not a number


var value='0411';

if(isNAN(value))
{
alert('this is not a number') ;
}else{
alert('this is a number') 

}


ANS : this is a number

undefined value and null value

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.

Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.


Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

undefined check not working in javascript

Checking undefined is not work when we go normal if statement, As like below

var id=$('#txt').val();

if(id != 'undefined')
{
// Our Code
}

"id" is var type, i.e mean unknown type, such as whether "id" is string, numeric, or even undefined.  
if "txt" is not defined in the page, then id's value is  undefined, so we shall check the type of operand with value.

By using "typeof" operator we resolve above issue. The "typeof" operator in JavaScript/Jquery allows you to probe the data type of its operand.

var item = 10;
alert(typeof item); This returns the type of item not value.


if(typeof id != 'undefined')
{
// Our Code


I hope this will help you to resolve the problem.

How to check if a variable is NOT undefined

Checking undefined is not work when we go normal if statement, As like below

var id=$('#txt').val();

if(id != 'undefined')
{
// Our Code
}

"id" is var type, i.e mean unknown type, such as whether "id" is string, numeric, or even undefined.  
if "txt" is not defined in the page, then its value is  undefined is a one of type, so we shall check the type of operand with value.

By using "typeof" operator we resolve above issue. The "typeof" operator in JavaScript/Jquery allows you to probe the data type of its operand.

var item = 10;
alert(typeof item); This returns the type of item not value.


if(typeof id != 'undefined')
{
// Our Code


I hope this will help you to resolve the problem.

What's the main difference between int.Parse() and Convert.ToInt32

string str = "199"

int.Parse(str)

  1. This method converts the string to integer. 
  2. If string variable 'str' is null, then it will throw ArgumentNullException. 
  3. If string 'str' has out of integer ranges, then it will throw OverflowException.
  4. If string 'str' is other than integer value, then it will throw FormatException. 


Convert.ToInt32(str)

  1. This method converts the string to integer. 
  2. If string str is null, then it will return 0 rather than throw ArgumentNullException.
  3. If string str represents out of integer ranges, then it will throw OverflowException. 
  4. If string str is other than integer value, then it will throw FormatException. 


What's the main difference between int.Parse() and Convert.ToInt32

string str = "199"

int.Parse(str)

  • This method converts the string to integer. 
  • If string variable 'str' is null, then it will throw ArgumentNullException. 
  • If string 'str' has out of integer ranges, then it will throw OverflowException.
  • If string 'str' is other than integer value, then it will throw FormatException. 


Convert.ToInt32(str)

  • This method converts the string to integer. 
  • If string str is null, then it will return 0 rather than throw ArgumentNullException.
  • If string str represents out of integer ranges, then it will throw OverflowException. 
  • If string str is other than integer value, then it will throw FormatException. 

find number of days in a month in sql



DECLARE @mydate DATETIME

SET @mydate = '1986/01/21'

SELECT DAY(DATEADD(DAY,-DAY(@mydate),DATEADD(MONTH,1,@mydate))) as DAYSCOUNT


Above query will return number days in a month. Actually it return last date of given month. This is simplest way to get number of days in a given month.


Attribute 'ng-app' is not a valid attribute of element 'html'

This is just a warning. You haven't enabled html5 in your application.That s why you are receiving this validation warnings.

Here i gave solution to rid out from this warnings.

After opened your MS VS, Select Tools->Options ->Text Editor- >HTML->Validation, Choose html5 in list, then restart your project.

If you are not find html5 in the list, you need to install html5, then do above step. Click here to down html5.

Again you are receiving such that warining, then prepend data- to the attribute name (e.g. data-ng-app, the warning lines gets disappear.


$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


HOW YOU DEFINE WEB.CONFIG ? CLICK HERE 2 FIND ANSWER


$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Element section is not supported in visual studio

You haven't enabled html5 in your application.That s why you are receiving this validation warnings.

Here i gave solution to rid out from this warnings. 

After opened your MS VS, Select Tools->Options ->Text Editor- >HTML->Validation, Choose html5 in list, then restart your project.

If you are not find html5 in the list, you need to install html5, then do above step. Click here to down html5.

CASCADE in SQL SERVER with example

Use the ON DELETE CASCADE option if you want rows deleted in the child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The advantage of the ON DELETE CASCADE option is that it allows you to reduce the quantity of SQL statements needed to perform delete actions.

select * from dbo.ProductDetails
select * from dbo.Products

CREATE TABLE [dbo].[Products](
[ProductID] [int] NOT NULL,
[ProductDesc] [varchar](50) NOT NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)) ON [PRIMARY]

CREATE TABLE [dbo].[ProductDetails](
[ProductDetailID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Total] [int] NOT NULL,
CONSTRAINT [PK_ProductDetails] PRIMARY KEY CLUSTERED
(
[ProductDetailID] ASC
)) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ProductDetails] WITH CHECK ADD CONSTRAINT
[FK_ProductDetails_Products] FOREIGN KEY([ProductID])
REFERENCES [dbo].[Products] ([ProductID])
ON UPDATE CASCADE
ON DELETE CASCADE

INSERT INTO Products (ProductID, ProductDesc)
SELECT 1, 'Bike'
UNION ALL
SELECT 2, 'Car'
UNION ALL
SELECT 3, 'Books'

INSERT INTO ProductDetails
([ProductDetailID],[ProductID],[Total])
SELECT 1, 1, 200
UNION ALL
SELECT 2, 1, 100
UNION ALL
SELECT 3, 1, 111
UNION ALL
SELECT 4, 2, 200
UNION ALL
SELECT 5, 3, 100
UNION ALL
SELECT 6, 3, 100
UNION ALL
SELECT 7, 3, 200

SELECT *
FROM Products
SELECT *
FROM ProductDetails

DELETE
FROM Products
WHERE ProductID = 1


DROP TABLE ProductDetails
DROP TABLE Products

cast vs convert in sql server

Cast() Function


The Cast() function is used to convert a data type variable or data from one data type to another data type. The Cast() function provides a data type to a dynamic parameter (?) or a NULL value.

Syntax
CAST ( [Expression] AS Datatype)

Convert() Function


When you convert expressions from one type to another, in many cases there will be a need within a stored procedure or other routine to convert data from a datetime type to a varchar type. The Convert function is used for such things. The CONVERT() function can be used to display date/time data in various formats.

Syntax

CONVERT(data_type(length), expression, style)

    Cast

    Cast is  ANSII Standard
    Cast cannot be used for Formatting Purposes.
    Cast cannot convert a datetime to specific format

    Convert

    Convert is Specific to SQL SERVER
    Convert can be used for Formatting Purposes.For example Select convert (varchar, datetime, 101)
    Convert can be used to convert a datetime to specific format

What is difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar


  • ExecuteNonQuery : Use for data manipulation such as Insert, Update, Delete.
  • ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
  • ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.

SQL Optimization Tips

•We shall use views and stored procedure instead of heavy-duty queries.
This can reduce network traffic, because your client will send to server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see.
 
• Use table variables instead of temporary tables. Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only.

 • Try to use constraints instead of triggers, whenever possible. Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers,whenever possible.

• Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL
statement does not look for duplicate rows, and UNION statement does
look for duplicate rows, whether or not they exist.

• Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance
degradation, you should use this clause only when it is necessary.

• Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in
comparison with select statements. Try to use correlated sub-query or
derived tables, if you need to perform row-by-row operations.

• Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the
GROUP BY clause. When you use GROUP BY with the HAVING clause, the
GROUP BY clause divides the rows into sets of grouped rows and
aggregates their values, and then the HAVING clause eliminates
undesired aggregated groups. In many cases, you can write your select
statement so, that it will contain only WHERE and GROUP BY clauses
without HAVING clause. This can improve the performance of your query.

• If you need to return the total table's row count, you can use
alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the
total table's row count, it can take very many time for the large
table. There is another way to determine the total row count in a
table. You can use sysindexes system table, in this case. There is
ROWS column in the sysindexes table. This column contains the total
row count for each table in your database. So, you can use the
following select statement instead of SELECT COUNT(*): SELECT rows
FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So,
you can improve the speed of such queries in several times.

• Include SET NOCOUNT ON statement into your stored procedures to stop
the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive
the message indicating the number of rows affected by a T-SQL statement.

• Try to restrict the queries result set by using the WHERE clause.
This can results in good performance benefits, because SQL Server will
return to client only particular rows, not all rows from the table(s).
This can reduce network traffic and boost the overall performance of
the query.

• Use the select statements with TOP keyword or the SET ROWCOUNT
statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller
result set will be returned. This can also reduce the traffic between
the server and the clients.

• Try to restrict the queries result set by returning only the
particular columns from the table, not all table's columns.
This can results in good performance benefits, because SQL Server will
return to client only particular columns, not all table's columns.
This can reduce network traffic and boost the overall performance of
the query.
1.Indexes
2.avoid more number of triggers on the table
3.unnecessary complicated joins
4.correct use of Group by clause with the select list
5 In worst cases Denormalization

Index Optimization tips

• Every index increases the time in takes to perform INSERTS, UPDATES
and DELETES, so the number of indexes should not be very much. Try to
use maximum 4-5 indexes on one table, not more. If you have read-only
table, then the number of indexes may be increased.

• Keep your indexes as narrow as possible. This reduces the size of
the index and reduces the number of reads required to read the index.

• Try to create indexes on columns that have integer values rather
than character values.

• If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns in the
key as to enhance selectivity, with the most selective columns to the
leftmost of the key.

• If you want to join several tables, try to create surrogate integer
keys for this purpose and create indexes on their columns.

• Create surrogate integer primary key (identity for example) if your
table will not have many insert operations.

• Clustered indexes are more preferable than nonclustered, if you need
to select by a range of values or you need to sort results set with
GROUP BY or ORDER BY.

• If your application will be performing the same query over and over
on the same table, consider creating a covering index on the table.

• You can use the SQL Server Profiler Create Trace Wizard with
"Identify Scans of Large Tables" trace to determine which tables in
your database may need indexes. This trace will show which tables are
being scanned by queries instead of using an index.

• You can use sp_MSforeachtable undocumented stored procedure to
rebuild all indexes in your database. Try to schedule it to execute
during CPU idle time and slow production periods.
sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"

Collation in SQL SERVER



COLLATE is use to search the Sensitive data from the table. I have explained collation with example.

--Example - 1:

DECLARE @A VARCHAR(10)

SELECT @A = 'a'

IF (@A = 'A')

PRINT 'Match'

ELSE

PRINT 'No Match'

SELECT @A = 'a'

IF (@A = 'A' COLLATE SQL_Latin1_General_CP1_CS_AS)

PRINT 'Match'

ELSE

PRINT 'No Match'

--Example - 2:

--CREATE TEMP TABLE

CREATE TABLE #Emp([PassWord] VARCHAR(50))

--INSERT VALUES

INSERT INTO #Emp VALUES('Password')

INSERT INTO #Emp VALUES('password')

INSERT INTO #Emp VALUES('PassWord')

INSERT INTO #Emp VALUES('PassworD')

--SELECT

SELECT * FROM #Emp WHERE [PassWord] ='password'

--USING COLLATION

SELECT * FROM #Emp WHERE [PassWord] COLLATE Latin1_General_CS_AS ='password'

--KNOW ABOUT COLLATION

SELECT * FROM fn_helpcollations()

ALTER TABLE #EMP

ALTER COLUMN [Password] VARCHAR(50)

COLLATE Latin1_General_CS_AS

Normally we have 4 type of sensitivity on SQL Server (Case, Width, Accent, kanatype)


concatenate first and last name in sql server

Concatenate many rows into a single text string using SQL

Hi , Some times we need to show full names of user in report, i.e have concatenate first-name, surname, last-name in a column. there are multiple way to concatenate names to full-name. 

Here i have drawn one of best .

please find my query to concatenate first and last name in sql server


       --Create Temp Table

CREATE table #Emp(first_name varchar(50), middle_initial varchar(50), last_name varchar(50))
  
--Insert records to Temp Table
insert into #Emp
select 'Harshad', null, 'Krishna' union all
select 'Harshad', 'J.', 'Krishna' union all
select 'Harshad', 'J.', null union all
select 'Harshad', null, null union all
select null, null, null

select
    *,
            isnull(' ' + nullif(first_name, ''), '') +
            isnull(' ' + nullif(middle_initial, ''), '') +
            isnull(' ' + nullif(last_name, ''), '') AS FN,
    stuff
    (
        isnull(' ' + nullif(first_name, ''), '') +
        isnull(' ' + nullif(middle_initial, ''), '') +
        isnull(' ' + nullif(last_name, ''), ''),
        1, 1, ''
    )AS FullName
from #Emp

-- Clear Temp Table

DROP TABLE #Emp

NULLIF
NULLIF returns null if it comparison is successful.



SELECT '' + NULLIF('Harshad','Harshad')

it returns NULL.