Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Tuesday, February 28, 2017

Getting SQL Server admin access

Following commands will provide you admin access for SQL Server instance.

Step 1:  Run > Services.msc

Step 2: Stop SQL Server (Express)




Step 3: sc start mssql$sqlexpress -m -T3659 -T4010 -T4022




Step 4: sqlcmd -S [SQLInstanceName] -E
Example: sqlcmd -S ComputerName\sqlexpress -E

Step 5:
exec SP_ADDSRVROLEMEMBER 'domainname\username', 'sysadmin'
go
exit

Example:
exec SP_ADDSRVROLEMEMBER 'domainname\vxp1122', 'sysadmin'
go
exit


Step 6: sc start mssql$sqlexpress



FYI:
We also have admin access for (localdb)\v11.0 

Tuesday, June 02, 2015

Sql Server Restrict Memory usage

With growing of sql server database size and increase in page views of website, you might run in to memory crunch situation.

Please note:  You might run into memory crunch situation for number of reasons like memory leak in code, etc, but in this article we will be focusing on only one scenario that is restricting sql server memory usage.

Cause of Memory crunch situation:

By default if you have not restricted sql server memory usage, it can use upto 2147483647.
























Solution:

Restrict the memory consumption of SQL Server by changing this limit to something which is reasonably your server can handle.



































If you like commands to change the limit:

— Turn on advanced options
EXEC  sp_configure‘Show Advanced Options’,1;
GO
RECONFIGURE
;
GO

— Set max server memory = 3500MB for the server
EXEC  sp_configure‘max server memory (MB)’,3500;
GO
RECONFIGURE
;
GO

Reference:
https://sqlserverperformance.wordpress.com/2009/10/29/suggested-max-memory-settings-for-sql-server-20052008/


Special Thanks to my friend Pankaj Mishra for sharing this information.

Monday, April 27, 2015

Create xml file from sql server table


Following code will create xml file from sql server table.

SQL Server Table








XML Output

    >/blogs>
          2601
          Program to illustrate operator overloading from string
          blah blah blah
          2013-02-18 13:57:00
   
     ....
     ....
     ....
     ....
     ....



Script to convert sql server table to xml file

declare @XmlOutput xml

set @XmlOutput =
(select BlogId, Title, ContentValue, CreationDate from Blogs
FOR XML AUTO, ROOT('MyRoot'), ELEMENTS)

select @XmlOutput

Monday, July 07, 2014

Update Table from Another Table in SQL Server

Update Table from Another Table in SQL Server:  A simple scenario demonstrating how we can update Persons table with data from Employees table using update statement.  A simple but very effective query which can saves you from creating unnecessary cursor for updating from different tables.  By performance wise also Update statement is more efficient compared to creating update cursor.


Update DestTbl
Set DestTbl.ColumnABC = SourceTbl.ColumnXYZ
FROM    Employees SourceTbl
JOIN    Persons DestTbl
ON      DestTbl.KeyCol1 = SourceTbl.KeyCol5


Here:
SourceTbl stands for Source Table
DestTbl stands for Destination Table



Saturday, May 24, 2014

A connection was successfully established with the server, but then an error occurred during the login process. (Microsoft SQL Server, Error 233)

Error: A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (.Net SqlClient Data Provider)

Solution:

Step 1: Open SQL Server Configuration Manager

  • Go to Windows 8 Start screen.
  • Start typing in SQLServerManager11.msc if you are looking for SQL Server 2012 configuration manager. Type in SQLServerManager10.msc if you are looking for SQL Server 2008 configuration manager.
  • In the result panel you can see the SQLServerConfiguration Manager.
  • Click the icon to launch the SQL Server Configuration manager.
  • The configuration manager will open in MMC.



Step 2: Enable following configuration settings
  1. ensure Shared Memory protocol is enabled
  2. ensure Named Pipes protocol is enabled
  3. ensure TCP/IP is enabled, and s ahead of the Named Pipes in the settings

Login failed for user. (Microsoft SQL Server, Error 18456)

I was recently facing this error when created a SQL Server login and then try login using that newly created login.

Error: Login failed for user. (Microsoft SQL Server, Error 18456) (.Net SqlClient Data Provider)

Please note:
Solution is available on this link, but since microsoft has bad habit of link breaking issue; I have copied and pasted the solution for my reference.
http://support.microsoft.com/kb/555332



Cause:
Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.
Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.
Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can't verify the login. This might be because the Windows login is from an untrusted domain.

Solution:

Scenario 1: Configure SQL Server in Mixed Authentication Mode.

SQL Server 2012, SQL Server 2008, and SQL Server 2005
  1. Open SQL Server Management Studio. To do this, click Start, click All Programs, click Microsoft SQL Server 200x (where x is the version of SQL), and then click SQL Server Management Studio.
  2. Right-click the server, and then click PropertiesSee image. 
  3. On the Security page, under Server authentication, click the SQL Server and Windows Authentication mode option button, and then click OKSee image. 
  4. In the SQL Server Management Studio dialog box, click OK to restart SQL Server.

    For more information, see Choose an authentication mode in SQL Server Books Online.
SQL Server 2000
  1. Open the Enterprise Manager. To do this, click Start, click All Programs, click Microsoft SQL Server 2000, and then clickSQL Server Enterprise Manager.
  2. Expand the server group.
  3. Right-click the server, and then click PropertiesSee image. 
  4. Click the Security  tab. See image. 
  5. Under Authentication, click the SQL Server and Windows option button.
  6. Restart SQL Server for the change to take effect.

Scenario 2: Verify that the SQL Server login exists

If you are trying to connect to the SQL Server by using SQL Server Authentication, and the server is configured for mixed mode authentication, verify that the SQL Server login exists. For more information, see Create a login in SQL Server Books Online.

Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal.

If you are trying to connect to SQL Server by using Windows Authentication, verify that you are logged in to the correct domain. 

Friday, November 01, 2013

Delete all the rows from all the tables in SQL Server

If you are in situation where you just want empty database structure, without having data in it.

Run following select statement which will generate set of delete statement to delete all the records for all the tables in your database.

SELECT
'Delete from ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ';' 
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Type = 'BASE TABLE'
ORDER by TABLE_NAME


In case your database is large and you want to know status of which table is currently getting deleted you can use following:

SELECT
'Print(''Delete started for ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ''');' +
'Delete from ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ';' +
'Print(''Delete done for ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ''');'  +
'Print(''.............'');'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Type = 'BASE TABLE'
ORDER by TABLE_NAME

Sunday, August 25, 2013

SQL Server Performance Tuning and Query Optimization Videos

If you are like me, who don't get much chance to get your hands dirty in fine tuning sql server queries, then you must watch this videos.

I am really thankful to this guy, who has posted such a useful videos.

http://www.youtube.com/playlist?list=PL2900t3sPCl1MZi88lYsRLUcSled8wAMU

Frankly speaking their is lot of materials out their on this topic and I always avoid learning because of that.  This videos helped me to quickly get started to attack problem I was facing.

If you landed here searching how to improve performance of your website then along with database sql indexing you should also look for this checklist.
http://dotnetguts.blogspot.com/2012/09/all-about-aspnet-website-performance.html

Saturday, August 17, 2013

Adding Column to SQL Server using Database Defensive Programming Technique

Recently I have learned good way to add column to sql server using database defensive programming technique from my co-worker.  All the credit for this blog post goes to him.  Thank you sir incase you are reading this blog post. (I have purposefully avoid mentioning name of co-worker due to privacy reason.)

Following example is very simple and self explanatory, Incase if you didn't get anything then pass your comment in comment section.


BEGIN TRANSACTION
IF EXISTS(SELECT 1 from information_schema.tables 
          where table_name = 'MyTableName')
  BEGIN
    Print('Table Exist');

    --Add Column MyColumn
    IF NOT EXISTS(SELECT 1 from information_schema.columns 
                  where table_name = 'MyTableName' 
                  and Column_Name='MyColumn')
     BEGIN
 ALTER TABLE MyTableName ADD MyColumn varchar(345) NULL;
 Print('MyColumn Column Added');
     END

    ELSE
     
     BEGIN
 Print('MyColumn Column Already Exist');
     END



  END

Else
    BEGIN
  Print('Table does not Exist');
    END


IF @@ERROR <> 0
    BEGIN
        PRINT('Problem in running script, Rolling back');
        ROLLBACK TRANSACTION;
    END
ELSE
 BEGIN
  PRINT('Script Run Successfully');
        COMMIT TRANSACTION;
 END

Wednesday, June 26, 2013

OCIEnvCreate failed with return code -1 but error message text was not available. - Solution

Recently I was facing an issue with connecting to oracle.  I was keep on getting below error when trying to connect oracle through .Net Code.

Error: OCIEnvCreate failed with return code -1 but error message text was not available.


Cause of Error:
I am using Win 7 machine with Oracle Installed on it and using Oracle SQL Developer.  Few days back IT team at my company push updates and for some reason this updates image has uninstalled Oracle client on my machine.  Oracle Client being not installed on my system was the cause of this error.


Solution:
Check for Start > All Programs > Oracle - OraClient11g_home_64bit > Application Development > and Click on SQLPlus Icon.

If that Icon brings up following error, then you need to reinstall Oracle Client in order to pass through this error.







The drive or network connection that the shortcut 'SQL Plus.lnk' refers to is unavailable.  Make sure that the disk is properly inserted or the network resource is available, and then try again.


If you are able to see "SQL Command Prompt" on your machine, then you do have good copy of Oracle Client installed on your machine, so you need to verify your .Net code to see whether proper connection string is assigned and so on...

Following link might also help you...


Hope this helps you in narrow down your problem.

Sunday, September 16, 2012

Error: Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF

I run into situation where i have to insert explicit value for identity column and run into following error, which is expected. Incase you run into similar situation here is the solution to insert value into Identity column in SQL Server.

Error: Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.

Cause of error: Trying to insert record including ID field where ID field is IDENTITY Column.

Solution: 
1) Make sure that you are in situation where you really want to insert ID, If that is not the requirement than simply remove ID field from your insert statement and try to execute the insert statement again.

2) Since i was sure that i want to insert ID in Identity column, here is solution...

SET IDENTITY_INSERT YourTableName ON

INSERT INTO YourTableName
(IDENTITY Column, Column1...ColumnN)
VALUES
(IDENTITY Value, Value1, ...., ValueN)

SET IDENTITY_INSERT YourTableName OFF

Note:
Make sure that your insert statement does include all column name list, otherwise you will run into this error.

Error: 
Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'Users' can only be specified when a column list is used and IDENTITY_INSERT is ON.


Wrong Insert Statement
INSERT INTO YourTableName
VALUES
(IDENTITY Value, Value1, ...., ValueN)

Correct Insert Statement
INSERT INTO YourTableName
(IDENTITY Column, Column1...ColumnN)
VALUES
(IDENTITY Value, Value1, ...., ValueN)

Saturday, July 21, 2012

Error: Database could not be exclusively locked to perform the operation

You might receive "Database could not be exclusively locked to perform the operation" or many error like such when you are trying to perform operation on database which is already been used by process or some other users.

In order to obtain "Exclusive lock" to perform some critical database operation when someone is already using database you can perform following steps as described below to solve your problem.

Earlier I have blogged in context of restore error, but it is not limited to only restore and since this is very common error you get stuck when you are trying to do some critical database operation i have decided to explain step by step so that it can help me and many others like me who are in same situation. :)


Solution to obtain exclusive locked to perform database operations.


Step 1: Disconnect Connection.
To do so:   File > Disconnect Object Explorer

Step 2: Connect Connection
To do so:  File > Connect Object Explorer

Step 3: Open "New Query" window and run following command
use master
Note: Above command will make your current database to master which is important before we run following sequence of command.

Step 4: Copy and paste following sequence of command in Query window.  Replace the word "MyDatabaseName" with Database name you are trying to get exclusive access.

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH ROLLBACK AFTER 30 

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH NO_WAIT

ALTER DATABASE MyDatabaseName SET MULTI_USER WITH ROLLBACK IMMEDIATE; 


You are now done and you can now try the command or operation you were trying to perform earlier which was giving you "Database could not be exclusively locked to perform the operation" error. 

Monday, April 16, 2012

How to avoid multiple database request to improve performance

It is not good to execute multiple db request for loading single page.  Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database.

In order to improve performance you should execute single stored proc and bring multiple resultset in to single db request.  In this article i will explain you how to avoid multiple database request and how to bring multiple resultset into single db request.

Consider a scenario of loading a Product Page, which displays

  • Product Information and
  • Product Review Information

In order to bring 2 database request in single db request, your sql server stored proc should be declared as below.

SQL Server Stored Proc

CREATE PROCEDURE GetProductDetails
@ProductId bigint,
AS
SET NOCOUNT ON

--Product Information
Select ProductId,
ProductName,
ProductImage,
Description,
Price
From Product
Where ProductId = @ProductId


--Product Review Information
Select ReviewerName,
ReviewDesc,
ReviewDate
From ProductReview
Where ProductId = @ProductId




Asp.net, C# Code to bring multiple db request into single db request

Code Inside Data Access Class Library (DAL)

public DataSet GetProductDetails()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "GetProductDetails";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataSet dsResultSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);

try
{
    var conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"];
    string strConnString = conString.ConnectionString;
    SqlConnection conn = new SqlConnection(strConnString);

    cmdToExecute.Connection = conn;

    cmdToExecute.Parameters.Add(new SqlParameter("@ ProductId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _productId));

    //Open Connection
    conn.Open();

    // Assign proper name to multiple table
    adapter.TableMappings.Add("Table", "ProductInfo");
    adapter.TableMappings.Add("Table1", "ProductReviewInfo");
    adapter.Fill(dsResultSet);

    return dsResultSet;              
}
catch (Exception ex)
{
    // some error occured. 
    throw new Exception("DB Request error.", ex);
}
finally
{
    conn.Close();
    cmdToExecute.Dispose();
    adapter.Dispose();
}
}



Code Inside Asp.net .aspx.cs page

protected void Page_Load(object sender, EventArgs e)
{
   if (Request.QueryString[ProductId] != null)
   {
      long ProductId = Convert.ToInt64(Request.QueryString[ProductId].ToString());  
   
      DataSet dsData = new DataSet();

      //Assuming you have Product class in DAL
      ProductInfo objProduct = new ProductInfo();
      objProduct.ProductId = ProductId;
      dsData = objProduct.GetProductDetails();

      DataTable dtProductInfo = dsData.Tables["ProductInfo"];
      DataTable dtProductReviews = dsData.Tables["ProductReviewInfo"];

      //Now you have data table containing information
      //Make necessary assignment to controls
      .....
      .....
      .....
      .....
      .....  

    }
}


Hope above code gave you basic idea of why it is important to avoid multiple db request and how to bring multiple recordset with single db request.

Wednesday, July 13, 2011

Restore failed - Exclusive access could not be obtained because the database is in use

Error: Restore failed for Server 'ServerName\InstanceName'.  System.Data.SqlClient.SqlError: Exclusive access could not be obtained because the database is in use. 


TITLE: Microsoft SQL Server Management Studio
------------------------------
Restore failed for Server 'ServerName\InstanceName'.  (Microsoft.SqlServer.SmoExtended)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1539+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: Exclusive access could not be obtained because the database is in use. (Microsoft.SqlServer.Smo)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1539+)&LinkId=20476


Solution
Try running any of this command and then try to restore.

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

ALTER DATABASE MyDatabaseNameSET SINGLE_USER WITH ROLLBACK AFTER 30 

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH NO_WAIT

ALTER DATABASE MyDatabaseName SET MULTI_USER WITH ROLLBACK IMMEDIATE;

Source of Information

Tuesday, February 08, 2011

Delete All Stored Proc from SQL Server DB

If you need to delete all stored proc from sql server db, following script would be useful.

I have found this useful script from Mattberther's Blog

I have observed that his script won't delete stored procedure which has space in it.
Example: If stored procedure name is like "Category Insert" i.e. Procedure which has space in its name.

I have make line bold wherein i have add bracket to support this.

declare @procName sysname


declare someCursor cursor for
    select name from sysobjects where type = 'P' and objectproperty(id, 'IsMSShipped') = 0


open someCursor
fetch next from someCursor into @procName
while @@FETCH_STATUS = 0
begin
    exec('drop proc [' + @procName + ']')
    fetch next from someCursor into @procName
end


close someCursor
deallocate someCursor
go

Claim DB Space After Deleting Records in Table - Reduce DB Space

Recently I have delete 2 million unwanted records from my sql server database table, what i realise is even after deleting records, space used by database is not reducing.

After browsing help available on Internet, I found out

1) Whenever we delete records from table, sql server doesn't reduce size of database immediately.
2) Even after deleting table , sql server doesn't reduce size of database.
3) Instead of Freeing space for deleted records, sql server marks pages containing deleted records as free pages, showing that they belong to the table. When new data are inserted, they are put into those pages first. Once those pages are filled up, SQL Server will allocate new pages.

So In order to claim database space after deleting records in Table, go through following steps:

1) Check what is Size of your Database using following command?
Exec sp_spaceused

2) Delete Records from table, If you have already did that skip this step.

3) Run below command to claim unused database space.
DBCC SHRINKDATABASE(0)

DBCC SHRINKDATABASE command - Shrinks the size of the data and log files in the specified database.

Best Practise to use this command

  • A shrink operation is most effective after an operation that creates lots of unused space, such as a truncate table or a drop table operation.
  • Most databases require some free space to be available for regular day-to-day operations. If you shrink a database repeatedly and notice that the database size grows again, this indicates that the space that was shrunk is required for regular operations. In these cases, repeatedly shrinking the database is a wasted operation.
  • A shrink operation does not preserve the fragmentation state of indexes in the database, and generally increases fragmentation to a degree. This is another reason not to repeatedly shrink the database.
More reading on this command
http://msdn.microsoft.com/en-us/library/ms190488.aspx


Few other things of Interest
If you have Created, Alter or Drop any Database table recently then run below command.
DBCC UPDATEUSAGE(0)

DBCC UPDATEUSAGE(0) - Reports and corrects pages and row count inaccuracies in the catalog views. These inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.

More reading on this command
http://msdn.microsoft.com/en-us/library/ms188414.aspx


Example showing how this command helps me to reduce size of my database after deleting records from table.

1) Take Backup of your Production Database.

2) Take Backup of Table Scripts of your Production Database.

3) Create Test Database in Local Environment

5) Run Tables creation script

6) Restore Production Database to Test Database in local environment

I am assuming you are familiar with above steps, actual steps begin after this.
I am also assuming that you have already deleted unwanted records in table.

7) Check Size of your Database
Exec sp_spaceused


8) Run Update Usage command
DBCC UPDATEUSAGE(0)


9) Check Size of your Database
Exec sp_spaceused


10) Run Shrink Database command
DBCC SHRINKDATABASE(0)

11) Check Size of your Database
Exec sp_spaceused

If everything goes smooth then you would see that your database size is reduced.

Sunday, January 30, 2011

Error: A network-related or instance-specific error occurred while establishing a connection to SQL Server.

Error: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

If you encounter above error, while running your VS.Net, than first thing you should do is to check your web.config file to make sure that connection string is correct.

This problem might occur if you have recently

  • Change your PC Name
  • Installed new sql server instance but have not updated your web.config file with correct instance name.


Example:
Earlier you were using instance name "YourPCName\SQLExpress" but due to new sql server instance installation your instance name changed to "YourPCName\CustomInstanceName".

Below is sample connection string, where text in red is cause of problem.
Data Source=MyPCName\MySQLInstance;Initial Catalog=MyDBName;Integrated Security=True


Solution
Check Connection string in your vs.net solutions, web.config file and correct with new sql server instance name.

Tuesday, January 25, 2011

Related Links - FullText Search Query Example

In any application generating related links is little challenging and it is very hard to get accurate result.  I have try to create example of related link query which will fetch close result of what you are looking for.

Consider an example of any website with article section and if you are trying to give related links using fulltext search query of sql server, than following query would be helpful.

If you are new to fulltext search and would like to understand more on how fulltext search works in sql server

Step 1: Check whether fulltext search is installed
Select SERVERPROPERTY('IsFullTextInstalled')
If this query returns a value of '1' then the component is installed.



Step 2: Create FullText Catalog
Create FullText Catalog MyDBNameCatalog

Step 3: Create FullText Index on Table
Create FullText Index on ArticlesTable
(ArticleTitle)
Key Index PK_ArticleTable_ArticleID on MyDBNameCatalog
with Change_Tracking Auto


Step 4: Creating Query - Example Query Related Links for Article in SQL Server
Select ftt.Rank, *
from ArticleTable
Inner Join FreeTextTable(ArticleTable, ArticleTitle, 'ISABOUT("My Search Text")') as ftt
on ftt.[Key] = ArticleTable.ArticleId
Order by ftt.Rank desc


Step 5: Now you are ready to create stored procedure which can return related links

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[ArticleTable_ReleatedLinks_FullTextSearch]
@ArticleId bigint,
@ArticleTitle varchar(500),
@iErrorCode int OUTPUT
AS
SET NOCOUNT ON

set  @ArticleTitle = 'ISABOUT(' +  @ArticleTitle + ')'

SELECT Top 20
ArticleTable.[ArticleId],
ArticleTable.[ArticleTitle]
FROM ArticleTable
Inner Join FreeTextTable(ArticleTable, ArticleTitle, @ArticleTitle) as ftt
on ftt.[Key] = ArticleTable.ArticleId
Where
ArticleTable.ArticleId != @ArticleId
ArticleTable.IsDeleted = 0
Order by ftt.Rank desc
-- Get the Error Code for the statement just executed.
SELECT @iErrorCode=@@ERROR

To understand about how FreeTextTable query works and for more examples and syntax

Saturday, December 11, 2010

Messages Error 0xc0202009: Data Flow Task 1: SSIS Error Code DTS_E_OLEDBERROR.

I was getting following errors while Importing Excel file to SQL Server

Following is list of error details on Importing Excel 2007 to SQL Server 2008
Error 0xc0202009: Data Flow Task 1: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80004005  Description: "Could not allocate space for object 'dbo.MyTable'.'PK_MyTable' in database 'MyDatabase_1384_8481' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.".
 (SQL Server Import and Export Wizard)

Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  
The "input "Destination Input" (44)" failed because error code 0xC020907B occurred, and the error row disposition on "input "Destination Input" (44)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)

Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  
The ProcessInput method on component "Destination - MyTable" (31) failed with error code 0xC0209029 while processing input "Destination Input" (44). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure. (SQL Server Import and Export Wizard)

Error 0xc02020c4: Data Flow Task 1: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020. (SQL Server Import and Export Wizard) 

Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  
The PrimeOutput method on component "Source - 'ip-to-country$'" (1) returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)


Work Around to deal with this situation
I have observed that from last couple of month my database has grow unexpectedly without my knowledge, and that was main reason for this error.  So if you encounter this problem, don't follow solution blindly otherwise you would never solve root cause of problem.

Do following
  • Try to go through one by one table and check which table had grown unexpectedly.  Tip try from checking table in which rows are inserted automatically.  Example: Errorlog tables and other depends on your application.
  • Ones you find the that table, identify what is causing sudden growth, is it due to code change in application or due to some automatic script run by someone (virus) this problem is causing.  Try to fix that problem.
  • Best approach is to take backup of that table and delete that table and recreate it.  That will fix problem as lot of primary keys are free. 
  • After solving this root cause problem try to apply solution.


Solution
  • Make sure there is enough Hard Disk space where database files are stored on server.
  • Turn on AUTOGROW for file groups.

Now try to Import your Excel File, make sure that you follow all points mentioned in this blog post in order to Import Excel 2007 file to SQL Server.  

Sunday, September 12, 2010

Random Records in SQL Server based on Where Clause

How to get random records in SQL Server based on Where Clause

Syntax

Select Top [No. of Random Records you want]  *
from
(
Select  Col1, Col2
from ActualTableName
where
Col1 Like '%SearchWord%'
) VirtualTable
ORDER BY NEWID()
Note: VirtualTable is table that doesn't exist in database, it is just a placeholder name.


Example
Select Top 1 *
from
(
Select QuestionId, QuestionTitle
from ForumQuestion
Where
ForumQuestion.QuestionTitle Like @SearchKeyword
) MyTable
ORDER BY NEWID()

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape