Tuesday, 1 January 2013

How to find out the tables and columns having particular data in SQL?


How to find out the tables and columns that hold the particular data
 In some of the scenario a developer have to check is there any particular value is stored in the any of the table in the entire db. It is very hard to find out the column and table that holds the particular data, by calling select query for each and every table in the database.
Following store procedure will search the particular data that we are given as the paramaeter to stored procedure, in the all tables and coloumns in the entire db and return the results. If we want to perfect match of the search key given the second parameter as 1 else 0.
StoredProcedure for search a keyword in the entire database.
CREATE PROCEDURE FindMyData_String
    @DataToFind NVARCHAR(4000),
    @ExactMatch BIT = 0
AS
SET NOCOUNT ON

DECLARE @Temp TABLE(RowId INT IDENTITY(1,1),
SchemaName sysname,
TableName sysname,
ColumnName SysName,
DataType VARCHAR(100), DataFound BIT)

INSERT  INTO @Temp(TableName,SchemaName, ColumnName, DataType)
SELECT  C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
FROM    Information_Schema.Columns AS C
        INNER Join Information_Schema.Tables AS T
            ON C.Table_Name = T.Table_Name
    AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
WHERE   Table_Type = 'Base Table'
        And Data_Type In
        ('ntext','text','nvarchar','nchar','varchar','char')

DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)

SELECT  @SQLTemplate = CASE WHEN @ExactMatch = 1
    THEN 'If Exists(Select *
                  From   ReplaceTableName
                  Where  Convert(nVarChar(4000), [ReplaceColumnName])
                               = ''' + @DataToFind + '''
                  )
             Set @DataExists = 1
         Else
             Set @DataExists = 0'
    ELSE 'If Exists(Select *
                  From   ReplaceTableName
                  Where  Convert(nVarChar(4000), [ReplaceColumnName])
                               Like ''%' + @DataToFind + '%''
                  )
             Set @DataExists = 1
         Else
             Set @DataExists = 0'
    END,
    @PARAMETERS = '@DataExists Bit OUTPUT',
    @i = 1

SELECT @i = 1, @MAX = MAX(RowId)
FROM   @Temp

WHILE @i <= @MAX
BEGIN
    SELECT  @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName',
    QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)),
    'ReplaceColumnName', ColumnName)
    FROM    @Temp
    WHERE   RowId = @i

    PRINT @SQL
    EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT

    IF @DataExists =1
        UPDATE @Temp SET DataFound = 1 WHERE RowId = @i

    SET @i = @i + 1
END

SELECT  SchemaName,TableName, ColumnName
FROM    @Temp
WHERE   DataFound = 1
GO

Monday, 31 December 2012

How to get size of the database in SQL / SQL Azure?

Some of the case database exceeds the db size and got error while trying to insert new row into the db. Most of the case this will happen after some years of using database. So we cannot identify the issue very quickly and may be our application need to shut down for some days. To monitoring this issue we can create a user interface (if we needed) which showing currently used size of the database.

Query for getting size of the database in SQL / SQL Azure
To get the table wise size we can use following query, which returns the name of the tables with size of the table.
select    
      sys.objects.name, sum(reserved_page_count) * 8.0 / 1024 as size_in_MB 
from    
      sys.dm_db_partition_stats, sys.objects 
where    
      sys.dm_db_partition_stats.object_id = sys.objects.object_id
group by sys.objects.name
To get the entire database used size we can use following query.
select
      sum(reserved_page_count) * 8.0 / 1024 as size_in_MB
from
      sys.dm_db_partition_stats
GO

Friday, 23 November 2012

Copy tables from one database to another in SQL Server


You can  use the Generate SQL Server Scripts Wizard to help guide the creation of SQL script's that can do the following:
  • copy the table schema
  • any constraints (identity, default values, etc)
  • data within the table
  • and many other options if needed
Good example workflow for SQL Server 2008 with screen shots shown here.

Right Click on Database >> Tasks >> Generate Scripts >>
This will pop up Generate SQL Server Scripts Wizards >> Click on Next >> Select Database >> This will bring up a screen that will suggest to Choose Script Option.
On Choose Script Option Screen of Script Wizard under section Table/View Options Look at Script Data row and Turn the Option to True.
The Next Screen will ask about object types. Select all the objects that are required in the generated script. Depending on the previous screen it will show few more screen requesting details about the objects required in script generation.
On the very last screen it will request output options. Select the desired output options of Script to file, Script to Clipboard or Script New Query Window.3
Clicking on Finish button will generate a review screen containing the required objects along with script generating data.
Clicking on Finish button one more time will generate the requested output.
Similarly, if you want to generate data for only one table, you can right click on the table and follow almost a similar wizard. I am sure this neat feature will help everybody who has been requesting for it for a long time.

Tuesday, 6 November 2012

How to implement SQL Bulk Copy in SQL Server

SqlBulkCopy for insert multiple rows of data into table in SQL Server
Sometimes we need to insert bulk amount of data into a table in SQL. We can insert bulk data to SQL in different methods. Here we are going to demonstrate how to insert large amount of data using SQL Bulk Copy method.
Example of SQL BulkCopy method
Here we are going to insert multiple rows of sample data into Employee table. First of all create a table in SQL named Employee. After that  create sample data for employee table and finally this multiple rows of employee data insert into table using SQL bulk copy method.
 
Create a Table in SQL 
CREATE TABLE Employee
(
ID INT,
EmpName varchar(200),
Department varchar(200),
DOB DateTime
);

SQLMulkCopy Example in SQL Server
SQLMulkCopy Example in SQL Server
 
C# Code to generate sample data and insertion using SQL Bulk Copy
private void loadDataBySQLBulkCopy()
        {
            DataTable dtTblEmployee = new DataTable();
            dtTblEmployee.Columns.Add("ID", typeof(Int32));
            dtTblEmployee.Columns.Add("EmpName", typeof(String));
            dtTblEmployee.Columns.Add("Department", typeof(String));
            dtTblEmployee.Columns.Add("DOB", typeof(DateTime));

            DataRow dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 1; //Bind Data to Columns
            dtrow["EmpName"] = "Wazeem";
            dtrow["Department"] = "Admin";
            dtrow["DOB"] = "1990-10-16 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 2; //Bind Data to Columns
            dtrow["EmpName"] = "Aslam";
            dtrow["Department"] = "HR";
            dtrow["DOB"] = "1987-05-16 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 3; //Bind Data to Columns
            dtrow["EmpName"] = "John";
            dtrow["Department"] = "Finance";
            dtrow["DOB"] = "1992-12-11 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 4; //Bind Data to Columns
            dtrow["EmpName"] = "Mishal";
            dtrow["Department"] = "Infra structure";
            dtrow["DOB"] = "1989-04-01 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            SqlBulkCopy bulkCopy = new SqlBulkCopy(
                "server=TEST;database=TEST;uid=test;password=test",
                SqlBulkCopyOptions.TableLock);
            bulkCopy.DestinationTableName = "dbo.Employee";
            bulkCopy.WriteToServer(dtTblEmployee);

        }

How many classes can a single .NET DLL contain?

There’s a common question in a programming interview that sounds like this:
“How many classes can a single .NET DLL contain?”
I did a little research on the web and I saw that lots of people think that the number is unlimited. Well, in my opinion, this is wrong!
Let me clarify this! Inside MSDN there’s a section on Overview on .NET Framework that contains a section on Metadata and Self-Describing Components. In this section you will find out how metadata is stored inside a Portable Executable and what is the structure of Metadata. When you are looking inside “Metadata and the PE File Structure” , you will find out that each element of your program is stored in a “Metadata table”(one for classes, one for members, a.s.o.). Each element is identified by a “Metadata token” and it’s definition is: ”Each row of each metadata table is uniquely identified in the MSIL portion of the PE file by a metadata token.Metadata tokens are conceptually similar to pointers, persisted in MSIL, that reference a particular metadata table.”(see MSDN). After this section, there is an explanation of these tokens. “A metadata token is a four-byte number. The top byte denotes the metadata table to which a particular token refers (method, type, and so on). The remaining three bytes specify the row in the metadata table that corresponds to the programming element being described.
Let me stop here. If a class is identified in the metadata table using a metadata token and the metadata token is afour-byte number, this means that the number of classes that an assembly can contain is smaller than the biggest number on 3 bytes (the first byte is a connection to the metadata table type). The biggest number on 3 bytes is 2^24– 1 or 16777215.
Therefore, the maximum number of classes (and classes members) that a .NET assembly can contain is 16777215. Am I right? (Wait for comments!)
That’s nice, right? :)
If I’ll have the time, I’ll try to write some code that will generate an assembly with more than 16777215 classes and see if I can use it… :)

Tuesday, 30 October 2012

is not a valid identifier.

I wrote this select but i recive a not valid identifier error message why??!?!?!?


set @sql = ' SELECT eVisionDalsid..'+@InvolvedTable+'.HeatEditedChemistryID AS tabid, eVisionDalsid..Heats.HeatID AS hid, eVisionDalsid..'+@InvolvedTable+'.HeatID AS Expr3,
eVisionDalsid..'+@InvolvedTable+'.'+@FieldValue+' AS fieldvalue, eVisionDalsid..Heats.HeatNumber AS Expr5, eVisionDalsid..HeatOrders.OrderNumber AS Expr6
FROM eVisionDalsid..'+@InvolvedTable+' INNER JOIN
eVisionDalsid..Heats ON eVisionDalsid..'+@InvolvedTable+'.HeatID = eVisionDalsid..Heats.HeatID LEFT OUTER JOIN
eVisionDalsid..HeatOrders ON eVisionDalsid..Heats.HeatID = eVisionDalsid..HeatOrders.HeatID
WHERE (eVisionDalsid..'+@InvolvedTable+'.HeatEditedChemistryID = @IdRegister)'

exec @sql


this is the error message:

Server: Msg 203, Level 16, State 2, Line 30
The name ' SELECT eVisionDalsid..HeatEditedChemistry.HeatEditedChemistryID AS tabid, eVisionDalsid..Heats.HeatID AS hid, eVisionDalsid..HeatEditedChemistry.HeatID AS Expr3,
eVisionDalsid..HeatEdit' is not a valid identifier.

exec (@sql)