Friday, December 23, 2011

Import Excel Data into Mssql using SQL Statement

you need to run one line per line, if you run all SQL together.
you will get below error message:

Incorrect syntax near 'sp_configure' 


Please Follow below Step 
Step 1sp_configure 'show advanced options', 1
Output Message: Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.


Step 2reconfigure
Output MessageCommand(s) completed successfully.


Step 3sp_configure 'Ad Hoc Distributed Queries', 1
Output MessageConfiguration option 'Ad Hoc Distributed Queries' changed from 1 to 1. Run the RECONFIGURE statement to install.


Step 4reconfigure
Output MessageCommand(s) completed successfully.


Step 5: Run your SQL to import Excel Files


Insert Excel Data into New Table (Create New Table)

INSERT INTO myTableName
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=C:\Staffs.xls', 'SELECT * FROM [Sheet1$]')

Insert Excel Data into Existing Table
SELECT * INTO  myTableName FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=C:\Staffs.xls', 'SELECT * FROM [Sheet1$]')




SQL Code to import Excel Data into New Table in Database


sp_configure 'show advanced options', 1
reconfigure
sp_configure 'Ad Hoc Distributed Queries', 1
reconfigure


SELECT * INTO  myTableName FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=C:\Staffs.xls', 'SELECT * FROM [Sheet1$]')

SQL Code to import Excel Data into Existing Table in Database

sp_configure 'show advanced options', 1
reconfigure
sp_configure 'Ad Hoc Distributed Queries', 1
reconfigure

SELECT * INTO  myTableName FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=C:\Staffs.xls', 'SELECT * FROM [Sheet1$]')




Friday, September 30, 2011

Database owner is already a user in the database

Error : Msg 15110, Level 16, State 1, Procedure sp_changedbowner, Line 46
The proposed new database owner is already a user in the database

If you are getting above error message while changing the database owner. ‘DBuser’ cannot become the owner of the current database if it already has access/dbo access to the database through an existing alias or user security account within the database. To avoid this, drop the alias or ‘user’ within the current database first. here is the solution.


Use Database_Name;
sp_dropuser ‘DBUser’
sp_changedbowner ‘DBUser’


Back Up the Transaction Log When the Database Is Damaged

To create a backup of the currently active transaction log

  1. Execute the BACKUP LOG statement to back up the currently active transaction log, specifying:
    • The name of the database to which the transaction log to back up belongs.
    • The backup device where the transaction log backup will be written.
    • The NO_TRUNCATE clause.
      This clause allows the active part of the transaction log to be backed up even if the database is inaccessible, provided that the transaction log file is accessible and undamaged.
  2. Optionally, specify:
    • The INIT clause to overwrite the backup media, and write the backup as the first file on the backup media. If no existing media header exists, one is automatically written.
    • The SKIP and INIT clauses to overwrite the backup media, even if there are either backups on the backup media that have not yet expired, or the media name does not match the name on the backup media.
    • The FORMAT clause, when you are using media for the first time, to initialize the backup media and rewrite any existing media header.
      The INIT clause is not required if the FORMAT clause is specified.



This example backs up the currently active transaction log for the MyAdvWorks_FullRM database even though MyAdvWorks_FullRM has been damaged and is inaccessible. However, the transaction log is undamaged and accessible:

BACKUP LOG DBNAME
   TO MyAdvWorks_FullRM_log1
   WITH NO_TRUNCATE
GO

Thursday, September 29, 2011

10 reasons why go for SQL Server 2008


10.  Plug-in model for SSMS.   SSMS 2005 also had a plug-in model, but it was not published, so the few developers that braved that environment were flying blind.  Apparently for 2008, the plug-in model will be published and a thousand add-ins will bloom. 
9.  Inline variable assignment.  I often wondered why, as a language, SQL languishes behind the times.  I mean, it has barely any modern syntactic sugar.  Well, in this version, they are at least scratching the the tip of the iceberg. 
Instead of:
DECLARE @myVar int 
SET @myVar = 5

you can do it in one line:
DECLARE @myVar int = 5

Sweet. 
8.  C like math syntax.  SET @i += 5.  Enough said.  They finally let a C# developer on the SQL team. 
7.  Auditing.  It's a 10 dollar word for storing changes to your data for later review, debugging or in response to regulatory laws.  It's a thankless and a mundane task and no one is ever excited by the prospect of writing triggers to handle it.  SQL Server 2008 introduces automatic auditing, so we can now check one thing off our to do list.
6.  Compression.  You may think that this feature is a waste of time, but it's not what it sounds like.  The release will offer row-level and page-level compression.  The compression mostly takes place on the metadata.  For instance, page compression will store common data for affected rows in a single place. 
The metadata storage for variable length fields is going to be completely crazy: they are pushing things into bits (instead of bytes).  For instance, length of the varchar will be stored in 3 bits. 
Anyway, I don't really care about space savings - storage is cheap.  What I do care about is that the feature promised (key word here "promises") to reduce I/O and RAM utilization, while increasing CPU utilization.  Every single performance problem I ever dealt with had to do with I/O overloading.  Will see how this plays out.  I am skeptical until I see some real world production benchmarks.
5.  Filtered Indexes.  This is another feature that sounds great - will have to see how it plays out.  Anyway, it allows you to create an index while specifying what rows are not to be in the index.  For example, index all rows where Status != null.  Theoretically, it'll get rid of all the dead weight in the index, allowing for faster queries. 
4.  Resource governor.  All I can say is FINALLY.  Sybase has had it since version 12 (that's last millennium, people).  Basically it allows the DBA to specify how much resources (e.g. CPU/RAM) each user is entitled to.  At the very least, it'll prevent people, with sparse SQL knowledge from shooting off a query with a Cartesian product and bringing down the box.
Actually Sybase is still ahead of MS on this feature.  Its ASE server allows you to prioritize one user over another - a feature that I found immensely useful.
3.  Plan freezing.  This is a solution to my personal pet peeve. Sometimes SQL Server decides to change its plan on you (in response to data changes, etc...).  If you've achieved your optimal query plan, now you can stick with it.  Yeah, I know, hints are evil, but there are situations when you want to take a hammer to SQL Server - well, this is the chill pill.
2.  Processing of delimited strings.   This is awesome and I could have used this feature...well, always.  Currently, we pass in delimited strings in the following manner:
exec sp_MySproc 'murphy,35;galen,31;samuels,27;colton,42'

Then the stored proc needs to parse the string into a usable form - a mindless task.
In 2008, Microsoft introduced Table Value Parameters (TVP). 
CREATE TYPE PeepsType AS TABLE (Name varchar(20), Age int) 
DECLARE @myPeeps PeepsType 
INSERT @myPeeps SELECT 'murphy', 35 
INSERT @myPeeps SELECT 'galen', 31 
INSERT @myPeeps SELECT 'samuels', 27 
INSERT @myPeeps SELECT 'colton', 42

exec sp_MySproc2 @myPeeps 

And the sproc would look like this:
CREATE PROCEDURE sp_MySproc2(@myPeeps PeepsType READONLY) ...

The advantage here is that you can treat the Table Type as a regular table, use it in joins, etc.  Say goodbye to all those string parsing routines.
1. Intellisense in the SQL Server Management Studio (SSMS).  This has been previously possible in SQL Server 2000 and 2005 with Intellisenseuse of 3rd party add-ins like SQL Prompt ($195).  But these tools are a horrible hack at best (e.g. they hook into the editor window and try to interpret what the application is doing).  
Built-in intellisense is huge - it means new people can easily learn the database schema as they go.

Wednesday, August 3, 2011

LINQ - Aggregate Operators

Below code is to show the unique value:


Public Sub LinqSample1()
    Dim arr
Distinct() = {1, 1, 1, 2, 2, 3, 4, 4, 5, 5}

    Dim strUniqueFactors = 
arrDistinct.Distinct().Count()

    Console.WriteLine(
strUniqueFactors & " is unique value.")
End Sub



Result:
is unique value.

Monday, June 20, 2011

mysql - sql injection prevention

If you have ever taken raw user input and inserted it into a MySQL database there's a chance that you have left yourself wide open for a security issue known as SQL Injection.


SQL injection is someone inserting a SQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.


for PHP users, All you need to do is use the function mysql_real_escape_string.


echo "Escaped Evil Injection:";
$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 
$name_evil = mysql_real_escape_string($name_evil);
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";


Result
Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''


SQL Hacks      SQL Injection Attacks and Defense     Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

Tuesday, May 10, 2011

Microsoft Distributed Transaction Coordinator May Stop Responding in a Low Memory Situation

When a server is in low memory situation, the Microsoft Distributed Transaction Coordinator (MS DTC) process (Msdtc.exe) may stop responding (crash).


When MS DTC tries to manage new transactions, the attempt fails because of a lack of resources.


Workaround
To work around this problem, verify that the memory configuration of the computer is correct, and then correct the memory configuration if it is not.


Microsoft Fix
To resolve this problem, obtain the latest service pack for Windows 2000. For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
260910  How to Obtain the Latest Windows 2000 Service Pack

Tuesday, May 3, 2011

Pro LINQ - Language Integrated Query in C# - 2010


I found LINQ tutorials for C#, here i just share to who is interest