Archive for the ‘Explanations’ Category

 Cross Join: 
 Each row in the first table is paired with all the rows in the second table. 
if OBJECT_ID('tempdb..#a') is not null 
	drop table #a 

if OBJECT_ID('tempdb..#b') is not null 
	drop table #b 

create table #a 
	acol varchar(10) 
insert into #a values 

create table #b 
	bcol varchar(10) 
insert into #b values 

select * from #a 
select * from #b 

select * from #a cross join #b 

Read Full Post »

Command like Sql can be used to run sql scripts saved in disks. Therefroe if there is a bunch of scripts

(files) they can all be added with ttheir path and file name in notepad and have it saved with anyname with a

cmd extension. Then running this file would execute all the lines in the file.

Use “sqlcmd” instead of osql because “osql” cannot handle alot of special characters like the “£” sign.

Here is an example:
sqlcmd -S MyServerName -E -d My_dbName -i “C:\MyTSQL\MyScript.sql”

The above if run in commandline will execute the script in the path.

This is usefull when we need to run batches of scripts.

To make scripts upload/commit to a server by using the above command make sure the SP/Function or other

objects are alwasy dropped and recreated e.i. starts with the create statement as below:

--For SP:
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[mySP]') AND type in (N'P', N'PC'))


--For Function:
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[myUDF]') AND type in (N'FN', N'IF', 

N'TF', N'FS', N'FT'))

create FUNCTION [dbo].[myUDF]
	@var AS VARCHAR(100)

Read Full Post »

Assume the below scenario:

A system checks a stock level for a grocery store that sells 3 items and whenever a certain item runs out it flags up a message.

Say the 3 items are:

To make use of binary masking (also known as bitwise) to be able to track which needs to be highlighted, we need to do the following:

1) We will assign a binary number to each one of the item, 1 for denoting we need to flag a message and 0 f0r doing nothing. Each of the the items in turn will have a fixed position. So in this instance there are three position for three items and we can assign it as below:

Item Position Binary Value
—– ——— ————-
Mango 0 1
Orange 1 0
Apple 2 1

2) Now, we need a single decimal number that represents which items jave a binary 1 to flag a message and which don’t. To do that we use the Position value and treat that as the power of 2.
So, we use Position 1 and 3 (because those have the binary value 1 binded) and it should equate to:

(2^0) = 1
+ (2^2) = 4
Total = 5

3) The value 5 can then be sent to the section of the system which flags messages. It should then have a script to reverse it back to a binary number which is 101.

The position number is fixed and therefore can be easily be deduced as to which binary number is binded to whcih item.

This way by only sending an integer number we can for a group of item attached and interchagne flag data.

>Returns the binary representation of a number:

-- courtesy to a script somewhere in the internet
CREATE FUNCTION [csrt].[udf_ReturnBinaryPattern] 
	@Byte INT


    DECLARE  @Pattern CHAR(8) 
    SET @Pattern = '' 

    SELECT @Pattern = convert(VARCHAR,+(@Byte & 1) / 1) + 
    convert(VARCHAR,(@Byte & 2) / 2) + 
    convert(VARCHAR,(@Byte & 4) / 4) + 
    convert(VARCHAR,(@Byte & 8) / 8) + 
    convert(VARCHAR,(@Byte & 16) / 16) + 
    convert(VARCHAR,(@Byte & 32) / 32) + 
    convert(VARCHAR,(@Byte & 64) / 64) + 
    convert(VARCHAR,(@Byte & 128) / 128) 

    RETURN (@Pattern) 


>Optional – Explaning & bitwise AND operator:
The binary representation of 170 (a_int_value or A) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B) is 0000 0000 0100 1011. Performing the bitwise AND operation on these two values produces the binary result 0000 0000 0000 1010, which is decimal 10.

SELECT 170 & 75

Result is 10 (thisis a decimal number)

The & operator tranforms number or charters into binary and then adds them up:

170 = 0000 0000 1010 1010
75= 0000 0000 0100 1011
10 = 0000 0000 0000 1010

Another artice: http://sqlfool.com/2009/02/bitwise-operations/

Read Full Post »

The different options available to eliminate/handle decimals

declare @value as float = 123.9876
select ceiling(@value), floor(@value) -- eliminate decimals 
select round(@value,2)

Find triggers inside a database (Courtesy to Harry Lee)

select st.name, strig.name, st.name
from sys.triggers strig inner join sys.tables st
	on strig.parent_id = st.object_id inner join sys.schemas sch
	on st.schema_id = sch.schema_id

Format number as currency

SELECT CONVERT(varchar, CAST(987654321 AS money), 1) 

Find column names in a given table

SELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'dbo.Foo' --you can change text to other dataTypes

Note on – pivoting accuracy with numbers
I have seen from experience that when Pivoting its better to use float or decimal (if you results can contain fractional values) and not integers to get more accurate results. If integer is required then the numbers need to be converted after the Pivotting.

Check IF Table is empty

To chekc if a record or a certain record exists

if exists(select top 1 * from TableName) — use the where clause to check for a certain record

The if exists checks whether any rows were returned. If I use top 1 in the selected statement that supposedly sohuld be more optimized because it does not need to show the showl table.
The star is used so that it can just be copied and reused by just changing the table name.

Generate Scripts (Backup scripts)
Right click on a database
> Task
> Generate Scripts

Select the type of objects
Click the Advances button to see what how you want the script to be produced.

This way you would have all or your selected object include tables and its data all scripted out in a file.

Read Full Post »

--Proof of nulls and selects

declare @a table 
(col int)
insert into @a
select 1
select null
select 3 

select count(*) from @a -- counts nulls
select count('') from @a -- counts nulls
select count(1) from @a -- counts nulls

select count(col) SpecificColumn  from @a	-- only counts NON null 

--Proof of Sum and Null

create table #a 
	b int

insert into #a values (1)
insert into #a values (null)
insert into #a values (1)

select sum(b) from #a

Read Full Post »

	---------------- EOF ------------------

    RAISERROR('This is an example', 16, 1)
    --where 16 is the severity (values 0-10) does not throw an error but can be used produce warnings.
    -- 1 Is an integer from 0 through 255. Using a unique state number for each location can help find which section of code is raising the errors.


	PRINT 'Error Handled: ' + ERROR_MESSAGE()

IF OBJECT_ID('tempdb..##AnyGlobalTable') IS NOT NULL
	DROP TABLE ##AnyGlobalTable

Read Full Post »

/* My explation

Think of partition as the number of groups you want the ranking for.
Therefore it will assign a row number starting from 1 to the columns of which the same values appear in the columns specified in the partition section

So if you just have one column there it will count each and every row
If you have two columns it will start the count of rows from 1 for each time the columns values are different.
In other workds: if you have two columns it will count the ranks for two groups.

Let me explain:
Say you have a table with two fields.
In there you store names of fruits in one column and the colour in another:

Mango orange
Mango green
Mango yello

Melon orange
Melon greeen
Melon yellow

If you just use any one of the column to partintion it will give your the rank from 1 -6 (total number of rows = 6).
If you put both the names of the columnns then you have rank for both the groups from (1-3)

declare @a table
n varchar(50)
, c varchar(50)

SELECT 'Mango', 'Orange'
SELECT 'Mango', 'Green'
SELECT 'Mango', 'Yellow'
SELECT 'Melon', 'Orange'
SELECT 'Melon', 'Green'
SELECT 'Melon', 'Yellow'
order by 1, 2

select *
,row_number() OVER (PARTITION BY n ORDER BY n) NameOccurance
,row_number() OVER (PARTITION BY c ORDER BY c) ColourOccurance
,row_number() OVER (PARTITION BY n, c ORDER BY n) BothOccurance
from @a a
order by 1, 3

-- thik of partition as group
-- in plain english for every mango get the colour ranking ordered by the name mango

Read Full Post »

Older Posts »