" Live as if you were to die tomorrow. Learn as if you were to live forever.. "
- Mahatma Gandhi

How to reuse query execution plan?

Posted on November 24th, 2015 by Jnana Swain

Before a query, batch, stored procedure and dynamic sql statements begins execution in SQL server the batch gets compiled into a plan. Compiled plans stored into a part of sql server memory called plane cache. Then plan is executed to produce result. When next time that same batch again executed, server will search the plane […]

User friendly DATETIME Functions in SQL Server 2008

Posted on November 24th, 2015 by Monalisa Pradhan

 In SQL Server 2005, there is no specific datatype to store only a Date. You must use the DATETIME or SMALLDATETIME data types. In addition to the date you have entered, you always see a time component. You then need to format your output to display only the date component. So to avoid these SQL […]

Get Record Count of a table in SQL Server without doing a Table Scan

Posted on November 24th, 2015 by Arijit Rath

Sometimes there is a need to get the record count of every table in a SQL Server database. The common method used for achieving this is doing a select count(*) from table_name but this can create a lot of overhead in large tables present in large databases. The record count of every user table is maintained in the […]

Avoiding the use of Triggers in SQL Server

Posted on November 24th, 2015 by Arijit Rath

Sometimes we need to audit all DML operations for tables in a MSSQL database. There are many methods for achieving this, one of the most common approaches is using  DML Triggers . But DML triggers can be expensive so we can make use of  the OUTPUT clause which is a new TSQL feature available in SQL […]

SQL Server Update Statistics

Posted on November 24th, 2015 by Arijit Rath

Updating the statistics of all the tables regularly in your SQL Server Database is an integral part of Database Maintenance. This can be achieved in many ways. We can do this through a script or create a sql job scheduled to run at a certain time. SQL Server also has a database option called “Auto […]

How to use the Transact-SQL functions CONTAINSTABLE and CONTAINS to do a search on a full-text enabled table

Posted on November 24th, 2015 by Mritunjay Kumar

This tip demonstrates how to use the primary functions CONTAINSTABLE and CONTAINS, to search in a full text enabled table in MS SQL Server. 1. CONTAINS    CONTAINS is a conditional predicate and used in a where clause to search columns containing character-based data types.   This term looks for a match based on a […]

How to use double quotes in dynamic SQL statements

Posted on November 24th, 2015 by Jnana Swain

It is a common knowledge that if a query contains a double quote, it throws an error but if it contains a single quote, the statement is executed. For example, the following statement will cause error select * from customers where city=”bbsr” However, the single quote can be used in a SQL query . select * from customers where city=’bbsr’ You can also […]

How to insert more than one record using a single insert statement

Posted on November 24th, 2015 by Monalisa Pradhan

In SQL, after creation of table we insert data using INSERT keyword. Suppose we have to insert 10 records, we write 10 INSERT statement for inserting them. However, in SQL Server 20008  a new feature called Row constructor has been introduced which allows us to write a single INSERT statement for inserting more than one record at a […]

Using Inner Cursor in MySQL

Posted on November 24th, 2015 by Rashmita Devi

In MySQL,  inner cursor ( which means Cursor inside another Cursor) does not work properly for stored procedures. So you can use “BLOCK” in such situations.   For example, if you want to create a stored procedure to iterate through all the records of a Master table and update related records in the Child table, the following code snippet can help you […]

Some Useful Date Time conversion Tips in SQL

Posted on November 24th, 2015 by Monalisa Pradhan

1. How to convert Military time to standard time In SQL server 2008 there is one datatype present called “time”. So when we create a column with this datatype, generally it store time in 24 hours format. At the time of selecting also we get that 24 hours time. Using following query helps in getting time […]

How to INSERT, UPDATE or DELETE record in one statement

Posted on November 24th, 2015 by Monalisa Pradhan

Generally we write separate statements to INSERT, UPDATE or DELETE data based on certain conditions. But now in SQL Server 2008 there is a new feature present called MERGE statement using which we can INSERT, UPDATE or DELETE record in one statement. MERGE is a new feature which Microsoft has introduced with SQL Server 2008 […]

Advantage of sp_executesql over Exec

Posted on November 24th, 2015 by Jnana Swain

Both sp_executesql and exec are used to execute Transact-SQL statement and batch. But SP_EXECUTESQL uses query execution plan, where as EXEC() compiles query every time and creates a new query execution plan.     Example:-     exec DECLARE @NAME CHAR(100) SET @NAME = ‘jnana’ SET @QUERY = ‘SELECT *FROM EMPLOYEE WHERE NAME = ”’ + @NAME […]

Transact-SQL :- ROW_NUMBER()

Posted on November 24th, 2015 by Rashmita Devi

While creating query we may need a column which will hold the sequential number like 1, 2, 3… Also we may need to show that sequential number according to a particular partition. In that situation we can use the ‘ROW_NUMBER’ keyword. Below syntax can be followed :-   To get sequential number irrespective of any partition.  […]

New Line character and Forming a comma Separated String in SQL Server

Posted on November 24th, 2015 by Monalisa Pradhan

New Line character in SQL Server Generally we use ‘\n’ as new line character. If we write the same in SQL server Query Analyzer it won’t work. Different operating systems have a different way of understanding new line. Mac only understands ‘\r’ as new line, while Unix and Linux understand ‘\n’ as new line character. […]

Bulk Copy with Oracle using Array Binding

Posted on November 24th, 2015 by Saroj Dash

In an application one of the biggest overheads of data insertion into the database is making round trips to the DB for insertion purpose. ADO.Net provides a mechanism to copy a bulk of data to SQL server using SqlBulkCopy. But for inserting bulk data into the Oracle database we need the help of ODP.NET (Oracle Data […]

MySQL: Ordering values according to a predefined pattern

Posted on November 24th, 2015 by Abinash Gracharya

This one is a very interesting and tricky tip. In my recent project I faced a problem  executing a query to find all the records from a table in a given order. The Problem In MySQL we can order the records by – desc , asc or in RAND() to a particular field or for multiple fields. But what […]

How to use a comma seperated list as paramater to a stored procedure

Posted on November 24th, 2015 by Kavita Asnani

Suppose we have a simple query   Select * from tblPerson where profession in (‘Teacher’, ‘TL’, ‘Developer’)   If in the above query we need to pass the list of professions as parameter to a stored procedure. We obviously cannot pass the parameter string as   sProff = “‘Teacher’, ‘TL’, ‘Developer’”;   This would give […]

How to display tabular data in CLR proc

Posted on November 24th, 2015 by Neha Agarwal

To return a custom recordset of values obtained during processing in a CLR procedure to the caller. You can create your records using the SqlDataRecord class and then send them through SqlPipe. Before you create an instance of SqlDataRecord, you need to define its structure as an array of objects of the SqlMetaData class: SqlMetaData[] […]

Set the Recovery model of the database to Simple/Full

Posted on November 24th, 2015 by Kavita Asnani

The following code iterates through all the databases in SQL Server 2000and sets their Recovery model to “SIMPLE”   USE master GO — Declare a variable to store the value [database name] returned by FETCH. DECLARE @dbname sysname, @cmd varchar(1000) — Declare a cursor to iterate through the list of databases DECLARE db_recovery_cursor CURSOR FOR SELECT […]

Consuming No space for storing NULL value in table

Posted on November 24th, 2015 by Monalisa Pradhan

t the time of designing table, we create columns but later some of these columns are not used or rarely used. These columns always take NULL value. Storing NULL value in a column takes memory space leading to wastage of memory. To avoid this there is a new feature present in SQL Server 2008 i.e […]

Which one to use in a SQL query:-“Not Exists”/ Left Join / Not In”?

Posted on November 24th, 2015 by Pallavi Kar

It is quite a common request to create a Transact-SQL query to compare a parent and a child table and find out if there are any parent records that don’t have a corresponding record in the child table. Generally, this can be done with one of the three ways: So which one of the below is a better practice.Lets take a look. # […]

How to create temporary table in MySQL

Posted on November 24th, 2015 by Rashmita Devi

It is faster to get data from temporary table instead of getting data form DB tables with several filter conditions. Temporary tables are connection specific. When the current client session terminates all the temporary tables are automatically deleted. Temporary table with same name can be created with in different connections. Here is the syntax to […]

Use of cross apply to show ‘,’ separated values(SQL Server)

Posted on November 24th, 2015 by Manish Tiwari

The following approach can be helpful while showing multiple columns(‘,’ seperated) in a single row of a grid for a particular value.   SELECT Column1,Column1, –Column for which you need ‘,’ seperated values State = substring(EL.ORDER_list, 1, datalength(EL.ORDER_list)/2 – 1) from Table1 c cross apply (select state + ‘,’ as [text()] from Table2 where Condition FOR XML PATH(”)) […]

Importance of Max Degree of Parallelism in SQL Server

Posted on November 24th, 2015 by Arijit Rath

Max Degree of Parallelism is an important setting in a multi processor environment. A value of 0 indicates that all processors will be involved in the query execution process of large queries which consume a lot of cpu. This can sometimes cause issues on the server and result in degraded performance. This setting can be […]

SqlServer Query Optimization Tips

Posted on November 24th, 2015 by Naibedya Kar

Tip 1: Always use WHERE Clause in SELECT Queries while we don’t need all the rows to be returned. This will help to narrow the return rows else it will perform a whole table scan and waste the Sql server resources with increasing the network traffic. While scanning the whole it will lock the Table […]

MYSQL:Ordering A TextField Numerically

Posted on November 24th, 2015 by Manaswinee Mohapatra

While ordering the numeric values stored in a text field(having DataType as VarChar,Char,Text etc) in a MySQL table ,you may not be able to get the expected result. For example if your table contains a field “NUMBERS” which is of varchar type and having the values 1, 2, 3, 4, 5 upto 10.Then the query […]

How to add dynamic data in to the SQL Report header and footer

Posted on November 24th, 2015 by Sagarika Mishra

SQLReport has a layout section which can be used as report page header/footer, this report header and footer can contain any static text, image, lines etc. By default the page headers and footers are displayed on the first and last page of a report, this behaviour can be manipulated by the properties like PrintOnFirstPage orPrintOnLastPage of the page which […]

MySQL: Filter or Search Records Using Regular Expression

Posted on November 24th, 2015 by Manaswinee Mohapatra

We can filter or search records according to the matched Regular Expression in MySQL. For that the syntax will be SELECT Col1, Col2, Col3   FROM   table_name   WHERE Col1 REGEXP pattern Where Col1, Col2, Col3 is list of columns to be fetched.You can select any number of columns. Pattern is the regular expression to be matched […]

Making Inserts into from one table to another table excluding duplicates – without using cursor / temp table/ loop

Posted on November 24th, 2015 by Tejaswini Das

There may be scenarios where we need to insert data from one table another and avoid duplicate insertions. We could think about using cursor or temp table and loop through to check whether the record exist or not and if not then insert. But we can also achieve this by using LEFT JOIN with a single query   Here […]

SQL Server : Multiple record insert

Posted on November 24th, 2015 by Amrit Pattanayak

We may face some situation where we need to insert multiple records in a table.   Using MS SQL Server 2000/2005, following is the most common way. USE [Database Name] GO INSERT INTO Table_Name (Column1, Column2, Column3) VALUES (Valu11, Value21, value31) INSERT INTO Table_Name (Column1, Column2, Column3) VALUES (Valu12, Value22, value32) INSERT INTO Table_Name (Column1, Column2, […]

Get database connection string using UDL files

Posted on November 24th, 2015 by Naibedya Kar

Database connection string is simply a string variable containing all the detail for a database to which our application deals with. Connection string should be in proper format. It is always a good practice to get the connection string from a UDL file. UDL file is nothing but a text file which contains all the […]

How To Set Page Break in a report Conditionally

Posted on November 24th, 2015 by Sagarika Mishra

Sometimes we need to set page breaks after a particular number of records in a report, which can be achieved by using following steps. Steps : In the Tablix region, select the Detail Row. Right click on it. Click an Add Group ->Parent group In the Group By expression, add the Expression  =Ceiling(RowNumber(Nothing)/20),click ok . […]

MySQL: How to get the Particular Data Range

Posted on November 24th, 2015 by Rashmita Devi

If we want to fetch the data with in a particular Date range then we can use the INTERVAL keyword.   For example,   Let’s say I want to fetch the records which have been inserted with in last 10 days that means the records which are added with in 21/7/2009 to 30/07/2009(30/07/2009 is Totay’s […]

MySQL : Exporting The Resultset of a Table into CSV File

Posted on November 24th, 2015 by Manaswinee Mohapatra

To export the resultset of a table into a .csv file in MySQL we have to execute the following query. SELECT * INTO OUTFILE pathName FIELDS TERMINATED BY ‘,’ OPTIONALLY ENCLOSED BY ‘”‘ LINES TERMINATED BY ‘\n’ FROM tableName Where ‘pathname’ is the path along with the .csv file name and ‘tableName’ is your table. […]

SQL Server: Restrict the duplicate insertion of records to the database using Store Procedure

Posted on November 24th, 2015 by Rasmita Mohanty

There are several ways we can avoid duplicate record insertion in the database using various programming languages. But, it doesnt have to be from programs always we can avoid duplicate insertion of records from the database too.   Here I am going to explain one of the methods by which we can avoid duplicate record insertion in the SQL Server database […]

Run the existing SQL Script programmatically with SMO

Posted on November 24th, 2015 by Shibani Shubhadarshini

SMO ======== SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server.   We can integrate SMO into any .NET based applications. SMO is also compatible with SQL Server version 7.0, SQL Server 2000, and SQL Server 2005, which makes it easy to manage a multi-version environment. Following code is […]

Deleting Duplicate records in SQL Server

Posted on November 24th, 2015 by Rashmita Devi

As I have mentioned in one of my previous tips that using ROW_NUMBER() we can get the serial number which is here. Using the same ROW_NUMBER() function you can also easily delete the Duplicate Records present inside a table. Lets say I have a Users Table which is having duplicate records. I need to delete […]

Forming Comma Separated String in SQL Server

Posted on November 24th, 2015 by Manaswinee Mohapatra

To get the values of a particular field separated by commas in sql server we can use below queries. For handling null values in sql server we can use either COALESCE() or ISNULL() functions.COALESCE function Checks for the first not null in the list. If all arguments are NULL, COALESCE returns NULL. Below is the example […]

Using Having clause with Count function in SQL

Posted on November 24th, 2015 by Mohanish Das

While working on a query to count some rows based upon a condition I found an interesting thing.If you were to use the COUNT function in a query for a condition then we have to use the HAVING clause instead of  WHEREclause. So the following query would return error: $wrong_query = “SELECT count( `fk_mp` ) FROM […]

T- SQL: Query with case-sensitve functionality

Posted on November 24th, 2015 by Rashmita Devi

In SQL Server when we try to get the records by checking the data of a particular column having the Datatype as a Varchar type, then it does not check for Case-Sentitivity.   Lets say I have a Users Table having a column named as “FirstName” ofnChar DataType. It contains following records. PK        FirstName         LastName        PhoneNumber ——-   ————     […]

How to create folders in SQLReport server dynamically ?

Posted on November 24th, 2015 by Rupesh Nayak

In SQLReporting  we can create folders, datasource and deploy reports mannually by opening the report manager. Sometimes it becomes  very cumbersome process to access the report manager and create folders, datasources, deploy reports manually if we have a lots of things to do at same time.   Imports System Imports System.IO Imports CreateReportFolderDemo.RSService Imports System.Web.Services.Protocols […]

MSSQL-Insert records for columns where IDENTITY is set

Posted on November 24th, 2015 by Sankalan Panda

Imagine We have a database table where we have a column set as Primary Key, Identity ON and auto incremented by 1. By any chance we need to insert few records into this table (including the Primary Key column) by selecting from some other existing. What should we do?    We will remove the Identity […]

How to backup and restore MySQL database.

Posted on November 24th, 2015 by Partho Banerjee

Two ways to take backup of existing MySQL database: 1. Exporting tables to text files using MySQL dump. 2. Copying database files. (within same version) not recommended.   Exporting tables to text files using MySQL dump:   This is the best solution to keep backup of database so that we can restore it to any version of […]

Top with ties option in SQL Server

Posted on November 24th, 2015 by Madhusmita Rout

If you are required to select TOP N records from a table being ordered by a column,  you can use the following query:         SELECT TOP N [COLUMNNAME] FROM TABLENAME ORDER BY [COLUMNNAME]        But there is one problem with the above statement is that if the table has multiple records having the same value  as that of the selected list […]

How to select Random rows in SQL Server using TABLESAMPLE

Posted on November 24th, 2015 by Monalisa Pradhan

Sometimes our table contains large number of records where we need to retrieve some of them (randomly). The TABLESAMPLE clause in SQL Server allows to extract a sampling of rows from a table in the FROM clause. It limits the number of rows returned from a table in the FORM clause to a sample number […]

Store data temporarily on your page and finally insert it into database

Posted on November 24th, 2015 by Manish Tewari

Sometimes we want to do temporary operations on our data on the page and finally store it into database for this we can use following procedure : 1) Create a temporary table treating function :   public DataTable CreateTemptable() { DataTable dtAccessorial = new DataTable(); dtAccessorial.Columns.Add(“PK_ACCESSORIAL_MAP_ID”, typeof(int)); dtAccessorial.Columns.Add(“ACCESSORIAL_TYPE”, typeof(string)); dtAccessorial.Columns.Add(“ACCESSORIAL_VALUE”, typeof(int)); dtAccessorial.Columns.Add(“ACCESSORIAL_CHARGES”, typeof(double)); dtAccessorial.Columns.Add(“INSERT_UPDATE_FLAG”, typeof(int)); […]

Avoid Causing havoc with Live Site/DB

Posted on November 24th, 2015 by Sathyan R

It is very common for applications to have multiple builds – examples being Developer Build, Local Server Build, Client’s Staging (test) server build and finally the production build. Now when we use these there is every chance of fooling around with the Live Application “thinking” that we are working in some other copy. o    Always […]

How to use UPDATE with JOIN in SQL queries

Posted on November 24th, 2015 by Mritunjay Kumar

We use JOIN in the SELECT statement often to retrieve data from multiple related tables. But, some times we can get into a situation where we may need to use UPDATEstatement by joining multiple tables. Consider a situation: A table named as USER_DATA is there which contains user details. This table has one column(along with other columns) named as  IS_ACTIVE […]

Display summary report using a simple query in MYSQL

Posted on November 24th, 2015 by Madhusmita Pradhan

In MYSQL GROUP BY provide us a modifier called WITH ROLLUP, which will added an extra row to the output as a summary report. For Example: Suppose we have a Sales table having SalesId, ContactId and SalesTotal. If we need a summary report, which will display total SalesTotal group by its ContactId. This can be […]

SQLSERVER Transaction rollback

Posted on November 24th, 2015 by Chandrasekhar Nayak

In SQL SERVER, modifications to data can be rolled back using BEGIN TRANSACTION statement. In T-SQL programming, after the BEGIN TRANSACTION statement if data has been changed using any DML statement, then all these modifications can be rolled back to the previous consistent state which was present before to the BEGIN TRANSACTION statement. But once […]

MySQL: Using “ON DUPLICATE KEY UPDATE” while inserting record

Posted on November 24th, 2015 by Rashmita Devi

Sometimes we may have the situation where multiple users insert record into the same table simultaneously . Lets say the primary key for a table is an integer field and user executes an insert query by giving the value for the Id (Primary Key) field as “1”. But at the same time another user has […]

Using Regular Expressions with MySQL queries to Search

Posted on November 24th, 2015 by Sujata Mohanty

Regular expressions are a powerful tooI as most of you will agree but how does one use it with SQL queries ? Recently I had a requirement where I had to write a query that searches for the word “test” in a description field. Usually we use MYSQL “LIKE” or “Full Text” index queries to […]

How to get the Deleted Identity Numbers in SQL Server 2005

Posted on November 24th, 2015 by Rasmita Mohanty

How to get the Deleted Identity Numbers in SQL Server 2005 Lets have an Employee table in which some employee records are saved with the unique identity numbers for each employee. Now, suppose some records were deleted from the Employee table due to some reasons and now I want all the deleted records from Employee table,which may […]

Backup SQL Database Through Code In VB.NET

Posted on November 24th, 2015 by Amrita Dash

Using the SQL SMO object we can easily take backup of SQL database through code. Following is the sample code used take backup.     [VB.NET CODE STARTS] ‘–Reference added Imports Microsoft.SqlServer.Management.Smo Imports Microsoft.SqlServer.Management.Common   ‘–Declare the backup object Dim WithEvents oBackup As New Backup   ‘–Method to take backup Private Sub BackupSqlDatabase()   Dim […]

Get list of existing TRIGGERs in MYSQL

Posted on November 24th, 2015 by Madhusmita Pradhan

While MySQL has features like StoredProcedure and View, it doesn’t have any option for displaying TRIGGER list in the ‘Schemata’ tab (right) section of QueryBrowser. Generally, we need a third party control like MySQL Workbench to get the list of existing TRIGGER lists.But there is another way through which we can get existing trigger lists and that is from the Metadata(Data about data). […]

Renaming Database Objects

Posted on November 24th, 2015 by Dipali Chakra

A lot of times we need a change . While working on an existing database,  we may need to change the database name and in some cases want to rename existing database objects. This can be done in a few seconds. In SQL Server this can be done in this manner : 1. Renaming a […]

How to Escape Wildcard Characters While Searching in SQL Server

Posted on November 24th, 2015 by Devi Das

This tip demonstrates how to use special characters like _, %, [  to perform a wildcard search on string values stored in database (SQL Server in this instance) Let us take the example of a table named “TIPS“, which contains a TITLEcolumn (that holds the title of all Tips ). Now, If you want to search a […]

How to swap data between columns in SQL Server

Posted on November 24th, 2015 by Dipali Chakra

At times, we may accidently insert data into a wrong column if we have two identical columns (both having the same data type). To fix this later on we can delete the data from the wrong column and insert it in the proper one, but that becomes a lot of work if you know how to swap data between the two […]

Using SQL JOIN to get data from different tables conditionally

Posted on November 24th, 2015 by Mritunjay Kumar

Last day i came across a situation, where i needed to write a SELECTstatement which will use join with different tables but according to some conditions.  Lets take the below situation:   We have three tables as below : Table : MEMBERS; Columns : MEMBERID, MEMBERNAME, MEMBERPHONE Table : COMPANY; Columns : COMPANYID, FKMEMBERID, WORKPHONE Table : […]

Why not to use TEXT data type in SQL Server 2000

Posted on November 24th, 2015 by Devi Das

1st Tip:   In SQL Server 2000, VARCHAR data type can’t hold long strings. The maximum length it supports is 8000 characters, So if you want to store data more than that, then you can’t use VARCHAR. If you are using SQL Server 2005, then you have an alternative to useVARCHAR(MAX), but in SQL Server 2000 it […]

Retrieving List of DB created by user from SQL Express 2005

Posted on November 24th, 2015 by Shibani Shubhadarshini

To populate the databases in SQL Express 2005 we use SQL Server Management object(SMO). This process retrieves all databases created by user along with the system databases. For getting the list of databases created by users only we have to use IsSystemObject property of databases. If the property is False then these are the databases […]

Executing SSIS package from local machine using C# code

Posted on November 24th, 2015 by Gourav Sharma

Before working on C# code you first need to make sure that you have Integration Services and Business Intelligence from Sql Server 20005/2008 installed,then you can Create  SSIS Package on your local machine.    The code for C# is given below but first you need to add refernce for Microsoft.SqlServer.ManagedDTS and includeMicrosoft.SqlServer.Dts.Runtime You can check […]

Dealing with NULL values in SQL Server

Posted on November 24th, 2015 by Devi Das

In RDBMS missing data is represented by NULL. Generally it indicates that the data has not been entered into the Database or technically it indicates ‘value is unknown’. Since NULL is unknown so any operation with NULL will return NULL. E.g: SELECT 1 + NULL The above query will return NULL as result. NULL is […]

DATALENGTH() AND LEN()

Posted on November 24th, 2015 by Dipali Chakra

We have two functions in Sql server LEN()  and  DATALENGTH()  which give the same output at most of the time  but differ in some situations.                            LEN() returns the number of characters in the string or variable while  DATALENGTH() returns the number of bytes used to represent a string or expression. We have 4 different cases in which […]

Using “WITH TIES” SQL Clause

Posted on November 24th, 2015 by Dipali Chakra

If we are using SELECT TOP N query, then it returns exactly N records, and drops any record arbitrarily that has the same value as the last record in the result set. Suppose we want a report showing top 50 costly items. There may be a situation in which the price of 50th item is […]

How to copy data to an identical table in another database

Posted on November 24th, 2015 by Monalisa Chakraborty

This tip demonstrates how to copy data from one table to an identical table in another database. Let us take the following situation. We have two tables as below : Table : SourceTable ;  Columns : UniqueID, NameField, NumField ; DB :SourceDB Table : DestinationTable ;  Columns : UniqueID, NameField, NumField ; DB :DestinationDB So we […]

DateTime Mystery In SQL Server

Posted on November 24th, 2015 by Mukesh Nayak

In this tip I want to share one of the more interesting aspects of DateTime datatype which I came across while working in the recent past. We have worked on various aspects and format of DateTime datatype in C# and SQL Server. But here in this section we will discuss about the tick value of […]

How to return Modified data in SQL Server

Posted on November 24th, 2015 by Devi Das

In SQL Server, there is a cool functionality by which you can get the modified data as a result set. Suppose there is a table containing rating information about any post and we want to get user’s previous rating before updating the current / new rating. Then we might write our query like – Here […]

Think Before Using ‘Distinct’ Command Arbitarily

Posted on November 24th, 2015 by Dipali Chakra

Sometimes it is seen if the beginners are getting some duplicates in their resultset then they are using DISTINCT. But this has its own disadvantages. Distinct decreases the query’s performance. Because the normal procedure is sorting the results and then removing rows that are equal to the row immediately before it. DISTINCT compares between all fields […]

How to find DB size and table info in MYSQL

Posted on November 24th, 2015 by Satheeskumar A

1. To know the size of the databases We can use this query “SELECT table_schema “Data Base Name”, sum( data_length + index_length ) / 1024 / 1024 “Data Base Size in MB” FROM information_schema.TABLES GROUP BY table_schema” This will display all the databases and its related size in MB. But we can change the range of […]

INSERT, UPADTE or DELETE a row and return column/columns value with single query

Posted on November 24th, 2015 by Santosh Bisoyi

At times you may need to UPDATE a row from a Table and at the same time you would also want to get the column value from the same SQL UPDATE query. Following is a solution using SQL OUTPUT clause . SQL OUTPUT clause :     The OUTPUT Clause from SQL server provides a very […]

INSERT data from one table into another

Posted on November 24th, 2015 by Santosh Bisoyi

Sometimes you need to insert data from one table to another and there are different solutions for this. Following is the one of them. Data insertion from one table to another can be done either of the following ways : CASE-I ( When both source and destination table are exist ) Example : INSERT INTO Destination(FullName,ContactNum) […]

SQL Server Index – IV (Composite and Covering Index)

Posted on November 24th, 2015 by Pradip Sukla

In this section we will discuss about some other types of indexing i.e.Composite and Covering indexes.   Composite Index An index that consists of more than one columns is referred as composite index. Both clustered and non-clustered indexes can be composite index. SQL 2005 and 2008 supports up to 16 columns in a composite index. […]

SQLServer Index – III (Non-Clustered Index)

Posted on November 24th, 2015 by Pradip Sukla

In this section lets discuss in details on the other type of index i.e. Non-Clustered index.   Nonclustered index is a special type of index where its logical order does not match the way the datas are stored on the disk. Here the leaf node contains the index rows instead of data pages. Like the […]

SQL Server Index – I (Basics)

Posted on November 24th, 2015 by Pradip Sukla

The design and implementation of indexes are one of the most important component of any SQL Server database design as it speeds up the querying process by providing a quick access to the rows of the table. The SQL Server uses an index in the same way we use the book index which helps us […]

How to update field values partially in MySQL UPDATE statement?

Posted on November 24th, 2015 by Chittaranjan Pattnaik

Generally UPDATE statement is used to update a field value completely. But there may be situations when we need only part of the field value to be replaced with some other values. So in this case we can’t use the traditional UPDATE statement as it may not find all the matches for our search and […]

SQL Server Index – V (Index Fragmentation)

Posted on November 24th, 2015 by Pradip Sukla

Most of us are already aware about the benefits of indexes which can speed up the execution of queries, but in this tip we will discuss on the overhead that is associated with it and will also discuss on the way to reduce or fix it. Index Fragmentation is one of them.  Lets discuss what […]

Access data from remote database server using FEDERATED Storage Engine in MySQL 5.0 and up

Posted on November 24th, 2015 by Madhusmita Pradhan

Now a days we need to handle/correlate bulk of data those are located in different remote database servers. For handle this type of situtation, MySQL 5.0 and up provide us an option “FEDERATED STORAGE ENGINE”. This storage engine will give us facility for link more than one database tables those are exist in  same or […]

Find Stored Procedure (s)/Function(s) related to a Table(s) in Database

Posted on November 24th, 2015 by Damodaranaidu Betha

Sometime we need to know what are the stored procedures/functions that are using a particular table in a huge database. The following queries list all the stored procedures/functions which are currently using the table. SELECT Name FROM sys.procedures WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE ‘%Employee%’ GO –Searching for Empoloyee table and RateChangeDate column together SELECT Name FROM sys.procedures […]

Fetch Nth Column of a Table

Posted on November 24th, 2015 by Mayukh Roy

We have N number of columns in a database table. We need to fetch 4th column of the table directly. We can fetch it easily using the field name(say, nth_field): Select nth_field from tablename But, what if we need to make it dynamic? If we need to fetch the n’th column and end-user inputs the […]

Creating and inserting data to a table using the SELECT statement

Posted on November 24th, 2015 by Srikant Das

We have been mostly using the create command to create a table and thereafter we insert or copy the content of the source table to the destination table being created But there is another shortcut method which creates copy of a source table as well as inserts the data from the source to the destination […]

Limiting the retrieval of data in SQL Server 2008

Posted on November 24th, 2015 by POOJA PANDEY

I was given this task of retrieving limited number of rows by changing the Sql query ofSQL Server 2008. It is simply very easy if we try it in MySql. Here we just need to add a “LIMIT” clause after we write “ORDER BY” clause. For e.g. we can see here : Suppose we have […]

How to find those tables which do not have any auto-incremental column in SQL Server

Posted on November 24th, 2015 by Subhashish Chaki

In our project we need to find out those tables which do not have any auto-incremental column. We have approx 100 tables in our project. It is quite difficult task to search all the table one by one. So how does one resolve this problem? We have used the below query to solve this problem.  ; SELECT […]

How to preserve SQLite db in AIR application uninstallation/reinstallation

Posted on November 24th, 2015 by Debasmita Sahu

Suppose you have created a flex desktop application with SQLite database. And a user installed that application in his system and suppose during  use of that application he has entered some important data inside the database of that application. So when he uninstall that app to install a new version of that application then his […]

Remove Multiple Spaces from a string using SQL Server

Posted on November 24th, 2015 by Suman Kumari

In order to replace multiple spaces in a string with a single space, we can use in built function REPLACE. e.g. DECLARE @TestString AS VARCHAR(20) SET @TestString = ‘Test   String’ To remove the extra spaces we need to use SET @TestString= REPLACE(REPLACE(REPLACE(@TestString,’ ‘,’ %’),’% ‘,”),’%’,”) This will result into removal of extra multiple spaces giving result as ‘Test String’ […]

Secure Way Of Executing The Update Statement In Sql Server

Posted on November 24th, 2015 by Sisir Patro

There are a few people or we can say there not even a single person who does no mistakes in his life. Mistakes are unwelcomed by everybody. Nobody wants to do mistakes in his/her life. But the other part of this statement is also true, mistakes made people learn the exact things and made people […]

Self join and its usage

Posted on November 24th, 2015 by Dinesh Sahoo

Sometimes we wonder when to use Self joins. I was getting confused regarding its usage as a newbie. Sometimes, they are very useful as it can be used in place of nested queries maintaining the efficiency of our application. I would like to share one scenario where it was very useful to me. Problem: We […]

Random Unique Code Generator

Posted on November 23rd, 2015 by Sukant Shekhar

Challenge: I was given a scenario in which i need to represent a large number by few character it must be hard to break the code. For ex: A 8 digit number into 5-6 character. That too uniquely identified per number (i.e code corresponding to each number should not match the code corresponding to different […]

Using constraints in Dataset

Posted on November 23rd, 2015 by Naibedya Kar

As we all know Dataset plays a significant role while working with .net applications. Those who are new to dataset, it is just an in memory representation of table data. This object is sufficient to differentiate classic ADO and ADO.NET. Constraints are nothing but conditions applied to the table Column or Columns to maintain data […]

How to close a Connection object automatically when we close the associated Reader object

Posted on November 23rd, 2015 by Amit Mohapatra

In some situations we feel the need to close a SQL connection object immediately after the SQL query operation with a associated reader is complete. We can not close the connection before we complete all the operations related to the reader. Also we need to close the connection immediately after we finish the use of reader object. […]

Programatically copy data from one table to another in ADO.NET

Posted on November 23rd, 2015 by Soumya Patnaik

If you want to copy all the data from one table to another ,then this tip can be helpful to you. The following code snippet copies all the data from theEmployee Table to “Employee1” provided the tables have same columns and constraints.   Public Sub TranseferAllEmployeeData() Dim Sqlcmd As New SqlCommand Dim strSQL As String = […]

Retrieving dynamic Xml based record set

Posted on November 23rd, 2015 by Naibedya Kar

XML is a simple and flexible system for defining data formats. This is completely platform independent and adopted everywhere for representing complex documents and data structures. For data transmission on web, its having significant contribution. Now days it’s been the major use of XML to store both rowset (single table) and hierarchical (multiple-table) data in […]

Converting Datatable to xml string and viceversa

Posted on November 23rd, 2015 by Naibedya Kar

XML is a simple and flexible system for defining data formats. This is completely platform independent and adopted everywhere for representing complex documents and data structures. For data transmission on web, its having significant contribution. It is very common to use dataset in .NET applications. A dataset may contain a single table or multiple tables […]

Avoid Duplicate record insertion on page refresh in ASP.NET

Posted on November 23rd, 2015 by Rasmita Mohanty

Avoid Duplicate record insert on page refresh using ASP.NET One of most common issue which many of the web developers face in their web applications, is that the duplicate records are inserted to the Database on page refresh. If the web page contains some text box and a button to submit the textbox data to […]

Display line feeds in multiline text box even after saving it in database

Posted on November 23rd, 2015 by Sachin Kumar

Problem: While saving multiline text box values to database and then retrieving it, the line feed character is not displayed on retrieval. For instance, we use a multiline text box to enter address and as often the address consists of multiple lines which are created using the Enter key (carraige return character). Now if we […]

Store Java Class Object in Database

Posted on November 23rd, 2015 by Prem Mali

Sometimes developers need to store their Java class object in database. This tip demonstrate how we can store object into database and again access the stored Java object.   //Creating a simple class. public class SimpleExample implements Serializable{ //Member variable. private int intValue; private String string; public void setIntValue(int intValue){ this.intValue = intValue; } public […]