Archive for the ‘Database’ Category

How to select random row from a data table

1: Select a random row with Microsoft SQL Server:
SELECT TOP 1 column FROM tableORDER BY NEWID()
2: Select a random record with Oracle:
SELECT column FROM( SELECT column FROM tableORDER BY dbms_random.value )WHERE rownum = 1
3: Select a random row with MySQL:
SELECT column FROM tableORDER BY RAND()LIMIT 1
4: Select a random row with PostgreSQL:
SELECT column FROM tableORDER [...]

Leave a Comment

How to get CSV file using SQL Server management studio

I had a task to output or generate CSV file using SQL Sever management Studio.
After some searching and learning, I got the following steps to get my tasks done:
1: Open SQL Server Management Studio 2005.   Tools > Options > Query Results > SQL Server > General > Default destination for results;
      Set to “Results [...]

Leave a Comment

The text data type cannot be selected as DISTINCT because it is not comparable

When I tried to select a table which includes a text type field using distinct. I got these error:
The text data type cannot be selected as DISTINCT because it is not comparable
The solution is convert text to VARCHAR(MAX).
CONVERT(VARCHAR(MAX), text_type_filedname)
Varchar(Max) is a LOB datatype and has a max size of 2GB.

Leave a Comment

How to copy a table in SQL Server correctly ?

There is chance that we might need to make a copy of table in SQL Server. Most of time, maybe we can use the following script:
Select * INTO newTable FROM oldDB.dbo.oldTable
It is really simple, right ? But, Did you concern the Constraint ? For example: There is a primary key in old table, you can [...]

Leave a Comment

Sql Server: Must declare the scalar variable

When one of asp.net project was in develop stage, we always got the exception ‘Must declare the scalar variable  “@variableName” ‘
I checked and searched from internet, about this issue, there have been many different reasons and solutons. But seems all of them are not fit our case.
I had to check by myself. I focused [...]

Leave a Comment

Reset Identity column in SQL Server

For identity column in SQL Server, we have a command to easy to control it!
DBCC CHECKIDENT
1 : Resets the Identity value for the Customer table to 0 so that the next record added starts at 1.
     DBCC CHECKIDENT(’Customer’, RESEED, 0)
2: Check current identify value:
    DBCC CHECKIDENT (’tablename’, NORESEED)
3: Set the next ID start from [...]

Leave a Comment