Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Sunday, March 17, 2013

Top with ties and without ties

Image

Top clause with ties

[code language="sql"]--with ties
Select top(4) with ties * from test.dbo.emp order by salary[/code]

- Query will generate rows including additional rows that have the same value based on the SORT column \columns as the last returned rows

- Can only be used in SELECT Statement and if and only if there is an ORDER BY clause specified.

Monday, March 4, 2013

@@Identity, Scope_Identity() , Ident_Current('table_name') : Get last inserted record in a table - Sql Server

Select @@Identity

Gets the identity value entered into to the table in your current session.Scope of @@identity is not limited. If there is a trigger which would create an entry in another table, you will get the identity created in the last.

in other words:

It returns the last identity value generated for any table in the current session, across all scopes.

Select Scope_Identity()

It returns the last identity value generated for any table in the current session and the current scope.

Hence, if we consider the example given above the scope_identity would give the identity value generated by explicit insertion rather than the trigger.

Select Ident_Current('table_name') 

It returns the last identity value generated for a specific table in any session and any scope.

Scope_Identity equivalent for GUID:

http://stackoverflow.com/questions/1509947/sql-server-scope-identity-for-guids

Saturday, June 23, 2012

Database: Create User with "Create Proc Permission"

[code]
USE MASTER
CREATE LOGIN da WITH PASSWORD = '12345'

USE yourdatabasename
GO
CREATE USER da FOR LOGIN da

CREATE ROLE yourrolename

EXEC sp_addrolemember 'db_datareader',yourrolename
EXEC sp_addrolemember 'db_datawriter', yourrolename
EXEC sp_addrolemember @RoleName = 'yourrolename', @MemberName = 'da'

GRANT EXECUTE TO da
GRANT CREATE PROCEDURE TO da

GRANT ALTER ON SCHEMA::dbo TO yourrolename
[/code]

Wednesday, March 21, 2012

Tuesday, March 6, 2012

Useful Special Characters For Sql Server Dynamic Queries

Char(44) -- comma
Char(39) -- Single Quote
char(9) -- Tab
char(10) -- Line feed
char(13) -- Enter\Carriage return
Char(32) -- Space

Go to SSMS.. Type :

[code language="sql"]

Select Char(44)

[/code]

and see the magic :)

Monday, January 30, 2012

Find the table to which a given column belongs - Sql Server

[code]
SELECT * FROM sys.columns WHERE NAME LIKE '%ColumnName%'
[/code]
Result Set will contain object_ids in which the "ColumnName" exists. Use following queries to get the corresponding object names.
[code]
SELECT * FROM sys.objects WHERE object_id in (39879409,
729261853,
2044026513
)
[/code]

More civilized code goes here;)

[code]
SELECT * FROM sys.objects O
INNER JOIN sys.columns C
ON O.object_id = C.object_id
WHERE C.NAME LIKE '%ColumnName%'

[/code]