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


Wednesday, June 16, 2010

RESTORE DATABASE using command

I found this error message when i restore the database using the GUI and it appear this error message "Error 3154: The backup set holds a backup of a database other than the existing database"
It because of trying to restore database on an existing active database.

Solution:
RESTORE DATABASE DatabaseName
FROM DISK = 'C:\myDatabase.bak'
WITH REPLACE

Use WITH REPLACE when using RESTORE command when u saw above error message "Error 3154: The backup set holds a backup of a database other than the existing database"

Tested in MSSQL 2005

Friday, June 4, 2010

SQL @@ROWCOUNT

Returns the number of rows affected by the last statement. It will let you to do a checking on the record you updated.

If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

Example
USE DB2008;
GO
UPDATE User
SET JobTitle = 'Manager'
WHERE UserID = 'u10021'
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
GO

Tuesday, November 17, 2009

SQL Injection

SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.

The primary form of SQL injection consists of direct insertion of code into user-input variables that are concatenated with SQL commands and executed. A less direct attack injects malicious code into strings that are destined for storage in a table or as metadata. When the stored strings are subsequently concatenated into a dynamic SQL command, the malicious code is executed.



Example
UserID = Request.form ("userid");
var sql = "select * from UserTable where ID= '" + UserID + "'";
The user is prompted to enter the User ID. If she or he enters "jack", the query assembled by the script looks similar to the following:

select * from UserTable where ID = 'jack'

However, assume that the user enters the following:

jack; drop table UserTable--

In this case, the following query is assembled by the script:

select * from UserTable where ID = 'jack''; drop table UserTable--'

The semicolon (;) denotes the end of one query and the start of another. The double hyphen (--) indicates that the rest of the current line is a comment and should be ignored. If the modified code is syntactically correct, it will be executed by the server. When SQL Server processes this statement, SQL Server will first select all records in UserTable where ID is jack. Then, SQL Server will drop UserTable.

Input characterMeaning in Transact-SQL

;

Query delimiter.

'

Character data string delimiter.

--

Comment delimiter.

/* ... */

Comment delimiters. Text between /* and */ is not evaluated by the server.

xp_

Used at the start of the name of catalog-extended stored procedures, such as xp_cmdshell.

Saturday, September 12, 2009

Select Statement for Different Database

Database SQL Syntax
- Different databases using different sql statement

DB2
select * from table fetch first 10 rows only

Informix
select first 10 * from table

Microsoft SQL Server and Access
select top 10 * from table

MySQL and PostgreSQL
select * from table limit 10

Oracle 8i
select * from (select * from table) where rownum <= 10

Monday, August 10, 2009

Linked Servers


A linked server configuration allows Microsoft® SQL Server™ to execute commands against OLE DB data sources on different servers. Linked servers offer these advantages:


  1. Remote server access.
  2. The ability to issue distributed queries, updates, commands, and transactions on heterogeneous data sources across the enterprise.
  3. The ability to address diverse data sources similarly.



When setting up a linked server, register the connection information and data source information with SQL Server. After registration is success, that data source can always be referred to with a single logical name.

You can manage a linked server definition with stored procedures or through SQL Server Enterprise Manager:

With stored procedures:

- Create a linked server definition using sp_addlinkedserver. To view information about the linked servers defined in a given instance of SQL Server, use sp_linkedservers. For more information, see sp_addlinkedserver and sp_linkedservers.

- Delete a linked server definition using sp_dropserver. You can also use this stored procedure to remove a remote server. For more information, see sp_dropserver.

With SQL Server Enterprise Manager:

- Create a linked server definition using the SQL Server Enterprise Manager console tree and the Linked Servers node (under the Security folder). Define the name, provider properties, server options, and security options for the linked server. For more information about the various ways a linked server can be set up for different OLE DB data sources and the parameter values to be used, see sp_addlinkedserver.

- Edit a linked server definition by right-clicking the linked server and clicking Properties.

- Delete a linked server definition by right-clicking the linked server and clicking Delete.

Saturday, August 8, 2009

How Long Stored Procedure stay in Sql Server 2000 cache?

SQL Server 2000

once the execution plan is generated for a Stored Procedure, it stays in the procedure cache. Lazy writer only keep looking and throwing out unused plans out of the cache "only when space is needed in cache".

Below are some documented and undocumented DBCC commands available in SQL Server 2000 to deal and find more information about SQL Server cache.

To Monitor the cahce:

DBCC SQLPERF (LRUSTATS)
DBCC CACHESTATS
DBCC MEMORYSTATUS
DBCC PROCCACHE
To clean the cache:
DBCC FLUSHPROCINDB
DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE

You can read more from SQL 2000 Topic under "Lazy Writer", 'Freeing and Writing Buffer Pages' at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/architec/8_ar_sa_8unn.asp

Monday, May 11, 2009

awe enabled Option - MsSql 2005

In Windows Server 2003, you able change the Address Windowing Extensions (AWE) API to provide access to physical memory in excess of the limits set on configured virtual memory. The specific amount of memory you can use depends on hardware configuration and operating system support.

  • Windows Server 2003, Standard Edition supports physical memory up to 4 gigabytes (GB).
  • Windows Server 2003, Enterprise Edition supports physical memory up to 32 GB.
  • Windows Server 2003, Datacenter Edition supports physical memory up to 64 GB.

Extra Note

  • You are not running Express or Workgroup version of SQL Server. Please check here for further details about limitations in different versions of SQL Server.
  • you have enabled awe enabled option and set max server memory to the maximum memory you can allocate to SQL Server. This is applicatiable for 32 but versions of OS and not required in 64 bit version of Windows servers. Please check here for further details and how to configure the memoryfor SQL Server

Thursday, April 30, 2009

COMPUTE (Transact-SQL) - SQL Server 2005

Generates totals that appear as additional summary columns at the end of the result set. When used with BY, the COMPUTE clause generates control-breaks and subtotals in the result set.

USE Database;
GO
SELECT CustomerID, OrderDate, SubTotal, TotalDue
FROM Sales.SalesOrderHeader
WHERE ID = 1
ORDER BY OrderDate
COMPUTE SUM(SubTotal), SUM(TotalDue);

MERGE statement - SQL Server 2008 New Feature

The idea behind the MERGE statement is that the developer can construct TSQL data-manipulation language (DML) statements in which INSERT, UPDATE, or DELETE can occur in the same statement, based on different search conditions. I think this idea is very cool. The ability to complete multiple statements within one statement could potentially lead to less coding and increased performance.
In addition to this statement, another great feature has been added to the INSERT statement. In SQL Server 2008, the developer can issue multiple rows to be inserted without using a SELECT statement as the INSERT statement source. Instead, the VALUE clause of the INSERT statement can be used to specify sets of values separated by parentheses and commas.

Friday, January 16, 2009

sp_helpfile



sp_helpfile returns the physical names and attributes of the current database.

Attributes that returns are name, fileid, filename, filegroup, size, maxsize, growth and usage.

- it for ms Sql Server

Database Engine Stored Procedures

sp_add_data_file_recover_suspect_db sp_droptype
sp_add_log_file_recover_suspect_db sp_executesql
sp_addextendedproc sp_getapplock
sp_addextendedproperty sp_getbindtoken
sp_addmessage sp_help
sp_addtype sp_helpconstraint
sp_addumpdevice sp_helpdb
sp_altermessage sp_helpdevice
sp_attach_db sp_helpextendedproc
sp_attach_single_file_db sp_helpfile
sp_autostats sp_helpfilegroup
sp_bindefault sp_helpindex
sp_bindrule sp_helplanguage
sp_bindsession sp_helpserver
sp_certify_removable sp_helpsort
sp_configure sp_helpstats
sp_control_plan_guide sp_helptext
sp_create_plan_guide sp_helptrigger
sp_create_plan_guide_from_handle sp_indexoption
sp_create_removable sp_invalidate_textptr
sp_createstats sp_lock
sp_cycle_errorlog sp_monitor
sp_datatype_info sp_procoption
sp_dbcmptlevel sp_recompile
sp_dbmmonitoraddmonitoring sp_refreshview
sp_dbmmonitorchangealert sp_releaseapplock
sp_dbmmonitorchangemonitoring sp_rename
sp_dbmmonitordropalert sp_renamedb
sp_dbmmonitordropmonitoring sp_resetstatus
sp_dbmmonitorhelpalert sp_serveroption
sp_dbmmonitorhelpmonitoring sp_setnetname
sp_dbmmonitorresults sp_settriggerorder
sp_dboption sp_spaceused
sp_dbremove sp_tableoption
sp_delete_backuphistory sp_unbindefault
sp_depends sp_unbindrule
sp_detach_db sp_updateextendedproperty
sp_dropdevice sp_updatestats
sp_dropextendedproc sp_validname
sp_dropextendedproperty sp_who
sp_dropmessage

Wednesday, December 10, 2008

Clear Transaction Log in SQL Server 2005 database

  1. Backup DB
  2. Detach DB
  3. Rename Log file
  4. Attach DB
  5. New log file will be recreated
  6. Delete Renamed Log file.

Above just is 1 of the way to clear the transaction log file

Monday, December 1, 2008

SQL Combine 2 Different Table

This SQL is use to combine 2 different table together for other purpose.
SELECT ISNULL(a.Col1,b.Cola) , ISNULL(a.Col2,b.Colb)
FROM Table1 a
FULL JOIN Table2 b
ON a.Col1 = b.Cola

Here is 2 Different Table,
Table Name : Salary
NameSalary
emil1000
rayden2000


Table Name: Flight
FligtTicketPrice
Kuala Lumpur265
Bangkok878


Below Sql is use to combine above 2 Tables Become below 1 Table
SELECT ISNULL(a.Name,b.FlightTicket) AS Col1, ISNULL(a.Salary,b.Price) AS Col2 FROM Salary a
FULL JOIN Flight b ON a.Name = b.FlightTicket

Col1Col2
emil1000
rayden2000
Kuala Lumpur265
Bangkok878