Dynamic result ordering in SQL

| category: Programming | author: st
Tags:

There are several methods to implement the dynamic ordering of result returned by SQL query. The examples of stored procedures below use the Microsoft's demo database AdventureWorks.

USE AdventureWorks
GO

Sequence of IF..ELSE

The sequence of IF..ELSE looks not so pretty but is efficient and rapid. When you …

Random sequence in Transact SQL query

| category: Programming | author: st
Tags:

The rand() Transact SQL function produces a sequence of same numbers in the query. For example:

SELECT rand() AS rand_value, id
FROM
    (      SELECT 1 AS id
     UNION SELECT 2 AS id
     UNION SELECT 3 AS id
    ) AS t1;

This query shows the following result:

rand_value             id
---------------------- -----------
0,581556027773794      1
0 …

SQL Server: show size of tables

| category: Programming | author: st
Tags:

How much of disk space is used by tables?

DECLARE @TableInfo TABLE (
    table_name sysname,
    row_count int,
    reserved_size_kb nvarchar(50),
    data_size_kb nvarchar(50),
    index_size_kb nvarchar(50),
    unused_size_kb nvarchar(50)
)

INSERT INTO @TableInfo
EXEC sp_MSforeachtable 'sp_spaceused ''?'''

UPDATE @TableInfo
SET
    data_size_kb     = replace(data_size_kb, 'KB', ''),
    reserved_size_kb = replace(reserved_size_kb, 'KB', ''),
    index_size_kb    = replace(index_size_kb, 'KB', ''),
    unused_size_kb …