Recent Updates Toggle Comment Threads | Keyboard Shortcuts

  • Ishtiak Alam 11:32 am on September 29, 2014 Permalink | Reply  

    How to handle System.IO.FileLoadException: Mixed Mode Assembly 

    Today I am going to discuss how to handle System.IO.FileLoadException: Mixed Mode Assembly. Basically I was working on a C# application which executes a SQL script from the front end. For this purpose I had to use C# SMO (Server Management Object). I have added four .dll files in my ‘Reference’ folder-

    • Microsoft.SqlServer.Smo
    • Microsoft.SqlServer.Management.Sdk.Sfc
    • Microsoft.SqlServer.ConnectionInfo
    • Microsoft.SqlServer.SqlEnum

    All of the dll files had the runtime version 2.0.50727. When I ran the program, the console shows the error message-

    System.IO.FileLoadException

    System.IO.FileLoadException

    The error was occurred because the property of the application was set for .NET version 4. but the runtime version of the dll files was 2.0.50727.

    Thats why Mixed Mode error occurred. The solution is pretty simple. You have to add only 3 lines in your app.config file.

        <startup useLegacyV2RuntimeActivationPolicy=”true”>
            <supportedRuntime version=”v4.0″/>
        </startup>

    So the whole app.config file looks like

    <?xml version=”1.0″ encoding=”utf-8″ ?>
    <configuration>
      <connectionStrings>
            <add name=”test” connectionString=”Server=DACW0143\SQL2k8R2;Integrated security=SSPI;database=master”/>
      </connectionStrings>
        <startup useLegacyV2RuntimeActivationPolicy=”true”>
            <supportedRuntime version=”v4.0″/>
        </startup>

    </configuration>

    And the C# code is-

    using System.IO;
    using System.Data.SqlClient;
    using Microsoft.SqlServer.Management.Common;
    using Microsoft.SqlServer.Management.Smo;
    using System;
    using System.Configuration;

    namespace RunSqlFromCode
    {
        class Program
        {
            static void Main(string[] args)
            {
                FileInfo file = new FileInfo(@”D:\script.sql”); //*.sql file path
                string script = file.OpenText().ReadToEnd();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“test”].ConnectionString);
                Server server = new Server(new ServerConnection(conn));
                server.ConnectionContext.ExecuteNonQuery(script);
            }
        }
    }

    And the SQL Script(script.sql) looks like-

    GO
    create database study
    GO
    use study
    GO
    create table Detail
    (
    id int,
    name varchar (25),
    roll int,
    Address varchar(50)
    )
    GO

    Now this piece of code should run your sql script from your C# application.

    And one more important thing to know. ADO.NET classes under System.Data namespace do not know how to handle GO statement. That’s why I have used SMO for this program. If you want to use ADO.NET you have to split the script on “GO” command into smaller scripts and execute those individual scripts.

    Hope this will help you… 🙂

     

     

     
  • Ishtiak Alam 9:34 am on September 26, 2014 Permalink | Reply  

    Difference between SQL Server Mirroring and Replication 

    Both replication and mirroring are methods of transferring data from a primary database, to a secondary database or databases. Two common scenarios for this are to have a separate copy of the database for reporting purposes, or to have a copy of the database safely off site in the event of disaster on the primary database. In theory both Replication and Mirroring have the same purpose, to shift data from your database to other locations, but each method has a very different application and way of going about things.

    Mirroring:

    Database mirroring is a primarily software solution for increasing database availability. It maintains two copies of a single database that must reside on different server instances of SQL Server Database Engine.

    Replication:

    It is a set of technologies for copying and distributing data and database objects from one database to another and then synchronizing between databases to maintain consistency. Using replication, you can distribute data to different locations and to remote or mobile users over local and wide area networks, dial-up connections, wireless connections, and the Internet.

    The major differences between these two methods are mentioned below:

    Topic

     

    Mirroring Replication
    Components Principal server, mirror server, and witness server (Optional). Publisher, Subscribers, Distributor (Optional).
    Data Transfer Individual T-Log records are transferred using TCP endpoints. Replication works by tracking/detecting changes (either by triggers or by scanning the log) and shipping the changes.
    Server Limitation It is one to one. i.e. One principal server to one mirror server. * Central publisher/distributor, multiple subscribers.* Central Distributor, multiple publishers, multiple subscribers.

    • Central Distributer, multiple publishers, single subscriber.* Mixed Topology.
    Types Of Failover Automatic or manual Manual
    DB Access Mirrored DB can only be accessed using snapshot DB. The Subscriber Database is open to reads and writes.
    Recovery Model Mirroring supports only Full Recovery model. It supports Full Recovery model.
    Restoring State The restore can be completed using with NORECOVERY. The restore can be completed using With RECOVERY.
    Backup/Restore User makes backup & Restore manually. User creates an empty database with the same name.
    Monitor/ Distributer/ Witness Principal server can’t act as both principal server and witness server Publisher can be also distributer
    Types Of Servers All servers should be SQL Server. Publisher can be ORACLE Server.
    SQL Server Agent Dependency/Jobs Independent on SQL Server agent. Yes. Snapshot agent, log reader agent & Distribution agent (transactional replication)
    Merge agent (merge replication).
    Requirements
    • Verify that there are no differences in system collation settings between the principal and mirror servers.
    • Verify that the local windows groups and SQL Server logins definitions are the same on both servers.
    • Verify that external software components are installed on both the principal and the mirror servers.
    • Verify that the SQL Server software version is the same on both servers.
    • Verify that global assemblies are deployed on both the principal and mirror server.
    • Verify that for the certificates and keys used to access external resources, authentication and encryption match on the principal and mirror server.

     

    * Verify that there are no differences in system collation settings between the servers.

    • Verify that the local windows groups and SQL Server Login definitions are the same on both servers.
    • Verify that external software components are installed on both servers.
    • Verify that CLR assemblies deployed on the publisher are also deployed on the subscriber.
    • Verify that SQL agent jobs and alerts are present on the subscriber server, if these are required.
    • Verify that for the certificates and keys used to access external resources, authentication and encryption match on the publisher and subscriber serve
    Using With Other Features Or Components Database mirroring can be used with
    Log shipping, Database snapshots , Replication
    Replication can be used with log shipping, database mirroring
    DDL Operations DDL changes are applied automatically. Only DML changes to the tables you have published will be replicated.
    Database Limit Generally good to have 10 DB’s for one server. No limit.
    Latency There will not be data transfer latency. Potentially as low as a few seconds.
    Committed / Uncommitted Transactions Only committed transactions are transferred to the mirror database. Only committed transactions are transferred to the subscriber database.
    Primary key Not required. All replicated table should have Primary Key.
    Individual Articles No. Whole database must be selected Yes. Including tables, views, stored procedures, and other objects. Also filter can be used to restrict the columns and rows of the data sent to subscribers.
    FILESTREAM Mirroring does not support FILESTREAM. Replication supports FILESTREAM.
    DB Name It must be the same name. It must be the same name
    DB Availability In Recovery state, no user can make any operation.
    You can take snapshot.
    Snapshot (read-only).
    Other types (Database are available).
    Warm/ Hot Standby Solution When a database mirroring session is synchronized, database mirroring provides a hot standby server that supports rapid failover without a loss of data from committed transactions. When the session is not synchronized, the mirror server is typically available as a warm standby server (with possible data loss). It provides a warm standby solution that has multiple copies of a database and requires a manual failover.
    System Data Transferred Yes No

     

    Hope, the difference is now clear to you…. 🙂

     
  • Ishtiak Alam 7:02 am on August 18, 2014 Permalink | Reply  

    How to Find Most Executed Stored Procedure 

    We all know, we have to optimize a system for better performance.  Sometimes we can have dramatic effect on relieving the physical bottlenecks of the system and improving end-user experience. And that’s why it’s important to look at stored procedures that are called very often by taking a holistic approach. These procedures are necessary for a system and those can often be its backbone. We can find most expensive or executed stored procedure by simple DMV (Dynamic Management Views) query.

    The following DMV query shows the execution count of each stored procedure, sorted by the most executed procedures first.

    SELECT DB_NAME (SQTX.DBID) AS [DBNAME]
    ,OBJECT_SCHEMA_NAME(SQTX.OBJECTID, DBID) AS [SCHEMA]
    ,OBJECT_NAME(SQTX.OBJECTID, DBID) AS [STORED PROC]
    ,MAX(CPLAN.USECOUNTS) [EXEC COUNT]
    FROM SYS.DM_EXEC_CACHED_PLANS CPLAN
    CROSS APPLY SYS.DM_EXEC_SQL_TEXT (CPLAN.PLAN_HANDLE) SQTX
    WHERE DB_NAME (SQTX.DBID) IS NOT NULL AND CPLAN.OBJTYPE = ‘PROC’
    GROUP BY CPLAN.PLAN_HANDLE
    ,DB_NAME(SQTX.DBID)
    ,OBJECT_SCHEMA_NAME(OBJECTID, SQTX.DBID)
    ,OBJECT_NAME(OBJECTID, SQTX.DBID)

    ORDER BY MAX (CPLAN.USECOUNTS) DESC

    Hope, this will help you to tune your database. Have a good day… 🙂

     
  • Ishtiak Alam 11:45 am on August 4, 2014 Permalink | Reply  

    Solution: Cannot open SSIS Project in SQL Server 2008 R2 

    Today I will discuss about a solution of a problem you may face while working with SQL Server Integration Service. Sometimes when you are  going to open an existing or a new project in SSIS 2008 you may face an error saying ”

    —————————— 
    An error prevented the view from loading.
    —————————— 
    ADDITIONAL INFORMATION: 
    The specified module could not be found. (Exception from HRESULT: 0x8007007E) (System.Windows.Forms)

    Now the question is why is this occured??? If you uninstall the SQL server or Visual Studio and then reinstall it, you may face this problem. Again, if you have uninstalled a different version of  SQL server or Visual Studio you may face this for other versions of these software. This error won’t allow you to open any SSIS project. So, the solution of this problem quite simple though it was like searching needle in a haystack. 😛

    So the solution lies in the following 2 points-

    1) Go to your C:\Windows\System32 folder and check if msvcr71.dll exists. If not, download the dll and paste it to the mentioned folder.

    2) Just replace your files with a copy from another SQL Server 2008R2/Visual Studio 2008 Installation, that is working, as follows:
    C:\Program Files (x86)\Common Files\microsoft shared\MSDesigners8\msddslm.dll
    C:\Program Files (x86)\Common Files\microsoft shared\MSDesigners8\msdds.dll
    C:\Program Files (x86)\Common Files\microsoft shared\MSDesigners8\msddsf.dll
    C:\Program Files (x86)\Common Files\microsoft shared\MSDesigners8\msddslmp.dll
    C:\Program Files (x86)\Common Files\microsoft shared\MSDesigners8\msddsp.dll

     

    VOILA!!!

    And you are done. So if you find your SSIS working now, then cheers and if not –

    you know “Knowledge has no limit”. So, KHOJ-THE SEARCH …. 🙂

     
    • Les 2:47 pm on August 27, 2014 Permalink | Reply

      Solution number 2 did the trick for me. Thank you very much.

  • Ishtiak Alam 11:11 am on May 27, 2014 Permalink | Reply  

    Big Data and Hadoop 

    What is Big Data?

    A massive volume of both structured and unstructured data that is so large that it’s difficult to process with traditional database and software techniques.

    • Walmarthandles more than 1 million customer transactions every hour.
    • Facebook handles 40 billion photos from its user base.

     

    Volume, Velocity and Variety

    pic1

     

    Common BIG DATA PROBLEMS

    • Modeling true risk
    • Customer churn analysis
    • Recommendation engine
    • Ad targeting
    • Analyzing network data to predict failure
    • Threat analysis
    • Trade surveillance
    • Search quality
    • Data “Sandbox”

     

    WHY HADOOP?

    Answer: Big Datasets

    Big Data analytics and the Apache Hadoop open source project are rapidly emerging as the preferred solution to address business and technology trends that are disrupting traditional data management and processing.

    Enterprises can gain a competitive advantage by being early adopters of big data analytics.

     

    WHAT IS HADOOP?

    pic2

    Apache Hadoop is an open source software framework for storage and large-scale processing of data-sets on clusters of commodity hardware.

    • Hadoop adoption
    • HDFS
    • MapReduce
    • Ecosystem Projects

     

    HDFS

    pic3

     

    HDFS file write operation

    pic13

     

    HDFS file read operation

    pic14

     

    Hadoop Architecture

    Hadoop_1

     

    What is map reduce?

    pic4

     

    Key map reduce terminology concept

    pic5

     

    Map reduce: basic concept

    pic6

     

    Map reduce operation

    pic7

     

    Sample dataset

    pic9

     

    Map reduce paradigm

    pic10

     

    Map reduce example

    pic8

     

    Map reduce & HDFS

    pic11

     

    Comparing rdbms & Map reduce

    pic12

     
  • Ishtiak Alam 10:51 am on May 27, 2014 Permalink | Reply  

    Mirroring a SQL Server 

    Mirroring a database is not really a hard task to do. You just need these easy and simple 11 steps to start mirrored SQL Server. Doing it will not just improve your disaster recovery capabilities on your application, but also you are leveraging the high availability database mirroring feature you find in SQL Server 2005 and above, which means it will allow failover of database in the event you lose your main SQL Server.

    Before starting this, be sure that you have 3 SQL Servers in different locations for best results. 2 Servers need to have the identical SQL Server instance which means the same version (either Standard or Enterprise) also it’s highly recommended that also the service pack and if any cumulative updates are the same on both servers. But for the third server, it can be SQL Server Standard, Enterprise, Workgroup, or Express. Witness Server will be the one pinging the other 2 servers if there’s something wrong. This is the server that has the ability to recognize whether to initiate an automatic failover. This will not contain any database, that’s why it’s nonsense to use a SQL Server other than Express edition.

    1. Verify the following:
      1. You have 3 SQL Servers for Principal, Mirror and Witness
      2. SQL Server is using an Active Directory account. Ideally, use the same account for all SQL Servers.
      3. Primary Database is in Full Recovery model.
    2. Back up the database on the Principal SQL Server.
    3. Create a database with the same name from the Principal SQL Server on the Mirroring SQL Server, then restore the backup on the Mirroring SQL Server with the option to Overwrite the existing database checked and RESTORE WITH NORECOVERY option.You will notice it’s in a Restoring mode. Don’t panic, this is normal as you have chosen the NORECOVERY option and it will be in a permanent Restoring state to prevent users from accessing the database. It will be only user accessible if the database fails over to the Mirror and now the old Principal will go to the recovering state.

    4. Start the mirroring configuration process on the Principal SQL Server. Right-click the Database –> Properties –> Mirroring and click Configure Security.
    5. On the Include Witness Server screen, select Yes and click next.
    6. Now choose Principal SQL Server Instance:
    7. Now choose Mirror SQL Server Instance:
    8. Choose a Witness Instance:
    9. Now enter the SQL Server Service Accounts for each SQL Server Instance, but if all of your SQL instances are using the same account, then just leave it blank.
    10. Completing the Wizard:
    11. Start the mirroring:

    Hooray! you have mirrored your SQL! Go to both servers and it should look like this now.

    Note: You might find an issue when you start mirroring and encounter this error
    The mirror database, “YourDatabaseName”, has insufficient transaction log data to preserve the log backup chain of the principal database. This may happen if a log backup from the principal database has not been taken or has not been restored on the mirror database. (Microsoft SQL Server, Error: 1478)

    As the error suggests, you need to backup the Principal SQL Server Transaction Logs and Restore it to the Mirroring SQL Server using the same restore options when you restored the database. If this happens, you can cancel the wizard and start configuring again after this step from step 4.

     
  • Ishtiak Alam 8:27 am on May 19, 2014 Permalink | Reply
    Tags: SQL Server 2008,   

    Grouping by Multiple Rows to Single Row as A String 

    Today I will show how to group multiple column data in comma separated values in a single row grouping by another column. The problem is described below with figures:

    pic1

     

    Here is the sample script to build the sample data set.

    CREATE TABLE TestTable (ID INTCol VARCHAR(4))
    GO
    INSERT INTO TestTable (IDCol)
    SELECT 1'A'
    UNION ALL
    SELECT 1'B'
    UNION ALL
    SELECT 1'C'
    UNION ALL
    SELECT 2'A'
    UNION ALL
    SELECT 2'B'
    UNION ALL
    SELECT 2'C'
    UNION ALL
    SELECT 2'D'
    UNION ALL
    SELECT 2'E'
    GO
    SELECT *
    FROM TestTable
    GO

    Here is the solution which will build an answer to the above question.

    -- Get CSV values
    SELECT t.IDSTUFF(
    (
    SELECT ',' s.Col
    FROM TestTable s
    WHERE s.ID t.ID
    FOR XML PATH('')),1,1,''AS CSV
    FROM TestTable AS t
    GROUP BY 
    t.ID
    GO

    I hope this is an easy solution.

    Final Clean Up Act
    -- Clean up
    DROP TABLE TestTable
    GO

    Hope, I have made it clear. Thank you all.. 🙂

     
  • Ishtiak Alam 8:41 am on May 15, 2014 Permalink | Reply
    Tags: , XML   

    How to import a bunch of XML files from a directory in T-SQL 

    You will need to create a directory testxml on the c drive and put a bunch of XML files in there. If you don’t have any XML files then save the following two as file1.xml and file2.xml

    file1.xml

    XML
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    
    <MusicCollection>
     <Artist>
      <ArtistName>Pink Floyd</ArtistName>
     <Album>
      <AlbumName>Wish You Were Here</AlbumName>
      <YearReleased>1975</YearReleased>
      </Album>
     <Album>
      <AlbumName>The Wall</AlbumName>
      <YearReleased>1979</YearReleased>
      </Album>
      </Artist>
     <Artist>
      <ArtistName>Prince</ArtistName>
     <Album>
      <AlbumName>Purple Rain</AlbumName>
      <YearReleased>1984</YearReleased>
      </Album>
     <Album>
      <AlbumName>Lotusflow3r</AlbumName>
      <YearReleased>2009</YearReleased>
      </Album>
     <Album>
      <AlbumName>1999</AlbumName>
      <YearReleased>1982</YearReleased>
      </Album>
      </Artist>
     <Artist>
      <ArtistName>Incubus</ArtistName>
     <Album>
      <AlbumName>Morning View</AlbumName>
      <YearReleased>2001</YearReleased>
      </Album>
     <Album>
      <AlbumName>Light Grenades</AlbumName>
      <YearReleased>2006</YearReleased>
      </Album>
      </Artist>
      </MusicCollection>

    file2.xml

    XML
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    <MusicCollection>
     <Artist>
      <ArtistName>Pink Floyd</ArtistName>
     <Album>
      <AlbumName>Wish You Were Here</AlbumName>
      <YearReleased>1975</YearReleased>
      </Album>
     <Album>
      <AlbumName>The Wall</AlbumName>
      <YearReleased>1979</YearReleased>
      </Album>
      </Artist>
     <Artist>
      <ArtistName>Prince</ArtistName>
     <Album>
      <AlbumName>Purple Rain</AlbumName>
      <YearReleased>1984</YearReleased>
      </Album>
     <Album>
      <AlbumName>Lotusflow3r</AlbumName>
      <YearReleased>2009</YearReleased>
      </Album>
     <Album>
      <AlbumName>1999</AlbumName>
      <YearReleased>1982</YearReleased>
      </Album>
      </Artist>
    </MusicCollection>

    Now that we have our files we are ready to grab all the files in the directory. We will use a plain vanilla DOS dir command for this with the B switch so that we don’t get a lot of garbage returned. Here is what this block of code looks like

    T-SQL
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    IF OBJECT_ID('tempdb..#tempList') IS NOT NULL
    DROP TABLE #tempList
     
    CREATE TABLE #tempList ([FileName] VARCHAR(500))
     
    --plain vanilla dos dir command with /B switch (bare format)
    INSERT INTO #tempList
    EXEC MASTER..XP_CMDSHELL 'dir c:testxml /B'
     
     
    --delete the null values
    DELETE #tempList WHERE [FileName] IS NULL
     
    -- Delete all the files that don't have xml extension
    DELETE #tempList WHERE [FileName] NOT LIKE '%.xml'
     
    --this will be used to loop over the table
    alter table #tempList add id int identity
    go

    Now let’s see what has actually been inserted into the table

    T-SQL
    1
    
    select * from #tempList

    Output
    ———————

    FileName	id
    file1.xml	1
    file2.xml	2

    The following table will be used to store the XML.

    T-SQL
    1
    2
    3
    4
    5
    6
    
    CREATE TABLE [dbo].[XMLImport](
        [filename] [VARCHAR](500) NULL,
        [timecreated] [DATETIME] NULL,
        [xmldata] [xml] NULL
    ) ON [PRIMARY]
    GO

    Here is where the import happens, since we have to use dynamic SQL to do the XML import it is better to use SP_EXECUTESQL instead of EXEC since SP_EXECUTESQL has output parameters.
    I have put comments in this codeblock but if you need more information how exactly this works then leave me a comment.

    T-SQL
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    
    truncate table XMLImport --in case you want to rerun just this codeblock
    declare @Directory varchar(50)
    select @Directory = 'c:testxml'
     
    declare @FileExist int
    DECLARE @FileName varchar(500),@DeleteCommand varchar(1000),@FullFileName varchar(500)
     
    DECLARE @SQL NVARCHAR(1000),@xml xml
     
    --This is so that we know how long the loop lasts
    declare @LoopID int, @MaxID int
    SELECT @LoopID = min(id),@MaxID = max(ID)
    FROM #tempList
     
     
     
    WHILE @LoopID <= @MaxID
    BEGIN
     
        SELECT @FileNAme = filename
        from #tempList
        where id = @LoopID
     
        SELECT @FullFileName = @Directory + @FileName 
        
        exec xp_fileexist @FullFileName , @FileExist output
        if @FileExist =1 --sanity check in case some evil person removed the file
        begin
        SELECT @SQL = N'select @xml = xml 
            FROM OPENROWSET(BULK ''' + @FullFileName +''' ,Single_BLOB) as TEMP(xml)'
         
        -- Just like in the bedroom, this is where the magic happens
        -- We use the output functionality to fill the xml variable for later use
        EXEC SP_EXECUTESQL @SQL, N'@xml xml OUTPUT', @xml OUTPUT
         
        
        --The actual insert happens here, as you can see we use the output value (@xml)
        INSERT XMLImport ([filename],timecreated,xmldata)
        SELECT @FileName,getdate(),@xml
        
        SET @DeleteCommand = 'del ' +  @Directory + @FileName 
        --maybe you want to delete or move the file to another directory
        -- ** here is how to delete the files you just imported
        -- uncomment line below to delete the file just inserted
        --EXEC MASTER..XP_CMDSHELL @DeleteCommand
        -- ** end of here is how to delete the files
        end
     
        --Get the next id, instead of +1 we grab the next value in case of skipped id values
        SELECT @LoopID = min(id)
        FROM #tempList
        where id > @LoopID
    END

    So that is all the code that you need to make this happen, let’s see what is actually inserted into the table

    T-SQL
    1
    
    select * from XMLImport

    output
    ————————————————————————

    filename	timecreated		xmldata
    file1.xml	2009-04-29 09:18:42.313	<MusicCollection><Artist><ArtistName>Pink Floyd....
    file2.xml	2009-04-29 09:18:42.330	<MusicCollection><Artist><ArtistName>Pink Floyd....

    Attention/warning!!

    Here are a couple of warnings for you.

    xp_cmdshell
    It is not a best practice to have xp_cmdshell enabled. As a matter of fact beginning with SQL Server 2005, the product ships with xp_cmdshell disabled. If you try to run xp_cmdshell you will get the following message if it is not enabled
    Server: Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1

    SQL Server blocked access to procedure ‘sys.xp_cmdshell’ of component ‘xp_cmdshell’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘xp_cmdshell’ by using sp_configure. For more information about enabling ‘xp_cmdshell’, see “Surface Area Configuration” in SQL Server Books Online.

    To enable xp_cmdshell execute the following code

    T-SQL
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    EXECUTE SP_CONFIGURE 'show advanced options', 1
    RECONFIGURE WITH OVERRIDE
    GO
     
    EXECUTE SP_CONFIGURE 'xp_cmdshell', '1'
    RECONFIGURE WITH OVERRIDE
    GO
     
    EXECUTE SP_CONFIGURE 'show advanced options', 0
    RECONFIGURE WITH OVERRIDE
    GO

    OPENROWSET 
    In SQL Server 2005 and 2008 OPENROWSET is also disabled by default, if you try to run an OPENROWSET query then you will see the following message:

    Server: Msg 15281, Level 16, State 1, Line 1
    SQL Server blocked access to STATEMENT ‘OpenRowset/OpenDatasource’ of component ‘Ad Hoc Distributed Queries’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Ad Hoc Distributed Queries’ by using sp_configure. For more information about enabling ‘Ad Hoc Distributed Queries’, see “Surface Area Configuration” in SQL Server Books Online.

    To enable OPENROWSET and OPENQUERY you can use the previous script but instead of ‘xp_cmdshell’ you will use ‘Ad Hoc Distributed Queries’. The script to enable Ad Hoc Distributed Queries is below

    T-SQL
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    EXECUTE SP_CONFIGURE 'show advanced options', 1
    RECONFIGURE WITH OVERRIDE
    GO
     
    EXECUTE SP_CONFIGURE 'Ad Hoc Distributed Queries', '1'
    RECONFIGURE WITH OVERRIDE
    GO
     
    EXECUTE SP_CONFIGURE 'show advanced options', 0
    RECONFIGURE WITH OVERRIDE
    GO

    xp_fileexist
    The stored proc xp_fileexist is undocumented so be aware that it could change with a service pack or be removed all together

     
  • Ishtiak Alam 10:14 am on May 14, 2014 Permalink | Reply  

    HTML Parsing in SQL Server 

    Today I will discuss how to parse HTML in SQL Server. Suppose, there is a HTML statement which you want to save to your database and show only the content without the tag. How will we do that??? Probably there are many ways to do that. Today I will show you how to do it with a function. Lets start:

    First we see the code. Then I will explain.

     

    CREATE FUNCTION [dbo].[fn_parsehtml]
    (
    @htmldesc varchar(max)
    )
    returns varchar(max)
    as
    begin
    declare @first int, @last int,@len int
    set @first = CHARINDEX(‘<‘,@htmldesc)
    set @last = CHARINDEX(‘>’,@htmldesc,CHARINDEX(‘<‘,@htmldesc))
    set @len = (@last – @first) + 1
    while @first > 0 AND @last > 0 AND @len > 0
    begin
    —Stuff function is used to insert string at given position and delete number of characters specified from original string
    set @htmldesc = STUFF(@htmldesc,@first,@len,”)
    SET @first = CHARINDEX(‘<‘,@htmldesc)
    set @last = CHARINDEX(‘>’,@htmldesc,CHARINDEX(‘<‘,@htmldesc))
    set @len = (@last – @first) + 1
    end
    return LTRIM(RTRIM(@htmldesc))
    end

     

    Explanation:

    The mechanism is so simple. We know HTML tags. So, the procedure is to find out the position of  ‘<‘ and ‘>’ in the HTML statement for each tag. Then we will find the length. We can find the position of those by using CHARINDEX function. Then we will use the STUFF function which will replace the tag with ‘ ‘ that means empty string. We will continue this procedure in a loop until the end of the HTML statement. Then we can call the function with any HTML statement parameter. Example:

    select dbo.fn_parsehtml(‘<p>SQL Server is what you need.</p>  <p>You should follow the blogs. </p>’)

    The details of STUFF function and CHARINDEX is given below:

     

    Hope you have enjoyed the post. Please let me know if there is any mistakes and I will edit the post. Thank you.

     

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel