MS SQL Server

  Home  Databases Programming  MS SQL Server


“Learn MS SQL Server programming with hundreds of Interview Questions and Answers and examples.”



394 MS SQL Server Questions And Answers

282⟩ What Happens If NULL Values Are Involved in String Operations?

If NULL values are involved in string operations, the result will be string NULL values. The following tutorial script shows you some good examples:

SELECT 'GlobalGuideLine'+NULL;

GO

----------

NULL

SELECT LEN(NULL);

GO

----------

NULL

SELECT REVERSE(NULL);

GO

----------

NULL

 123 views

284⟩ What Happens If NULL Values Are Involved in Comparison Operations?

If NULL values are involved in comparison operations, the result will be Boolean NULL values. This behavior is very interesting because you would expect a comparison operation returns only one of the two values: TRUE and FALSE. But SQL Server may return you a third value: NULL.

The tutorial script below proves that "1>NULL" is not returning TRUE or FALSE. It is returning a third value, NULL:

IF 1>NULL PRINT '1>NULL is returning TRUE'

ELSE PRINT '1>NULL is not returning TRUE'

GO

1>NULL is not returning TRUE

IF NOT 1>NULL PRINT '1>NULL is returning FALSE'

ELSE PRINT '1>NULL is not returning FALSE'

GO

1>NULL is not returning FALSE

Another test proves that "'GGL'=NULL" is not returning TRUE or FALSE. It is returning a third value, NULL:

IF 'GGL'=NULL PRINT '''GGL''=NULL returns TRUE'

ELSE PRINT '''GGL''=NULL does not return TRUE'

GO

'GGL'=NULL does not return TRUE

IF NOT 'GGL'=NULL PRINT '''GGL''=NULL returns FALSE'

ELSE PRINT '''GGL''=NULL does not return FALSE'

GO

'GGL'=NULL does not return FALSE

 139 views

285⟩ What Happens If NULL Values Are Involved in Datetime Operations?

If NULL values are involved in datetime operations, the result will be datetime NULL values. The following tutorial script shows you some good examples:

USE GlobalGuideLineDatabase;

GO

SELECT GETDATE()+NULL;

GO

-----------

NULL

SELECT DATEDIFF(DAY, GETDATE(), NULL);

GO

-----------

NULL

 141 views

286⟩ What Happens If NULL Values Are Involved in Boolean Operations?

If NULL values are involved in Boolean operations, the result will vary depending on the operator type. For AND operator, FALSE takes precedence over NULL. The result can be summarized in a table below:

AND  TRUE FALSE NULL

TRUE true false null

FALSE false false false

NULL null false null

For OR operator, TRUE takes precedence over NULL. The result can be summarized in a table below:

OR TRUE FALSE NULL

TRUE true true true

FALSE true false null

NULL true null null

The tutorial script below shows you that NULL AND FALSE returns FALSE:

IF 0=NULL AND 0=1 PRINT 'NULL AND FALSE returns TRUE'

ELSE PRINT 'NULL AND FALSE does not returns TRUE'

GO

NULL AND FALSE does not returns TRUE

IF NOT (0=NULL AND 0=1)

PRINT 'NULL AND FALSE returns FALSE'

ELSE PRINT 'NULL AND FALSE does not returns FALSE'

GO

NULL AND FALSE returns FALSE

 129 views

287⟩ How To Replace NULL Values in Expressions using ISNULL()?

As you learned from provious tutorials, NULL values presented in expressions will cause the final results to be NULL. Sometimes, you want NULL values to be replaced with some default values, like 0, '', or 'NULL', so that expressions can be evaluated properly.

SQL Server offers a built-in function called ISNULL() to help you replacing NULL values in expressions:

ISNULL(expression, replacement)

-- Returns "expression", if it is not NULL

-- Returns "replacement", if "expression" is NULL

The tutorial example below shows you how to replace possible NULL values in @middle_initial:

USE GlobalGuideLineDatabase;

GO

CREATE PROCEDURE welcome

@first_name VARCHAR(20),

@middle_initial VARCHAR(1),

@last_name VARCHAR(20)

AS

PRINT 'Hello '+@first_name

+ ' '+@middle_initial

+ ' '+@last_name;

PRINT 'Hello '+@first_name

+ ' '+ISNULL(@middle_initial,'')

+ ' '+@last_name;

GO

EXEC welcome 'John', 'W', 'King';

GO

Hello John W King

Hello John W King

EXEC welcome 'John', NULL, 'King';

GO

Hello John King

The first PRINT statement in the second test returns a blank line becaus

 133 views

288⟩ How To Replace Given Values with NULL using NULLIF()?

Sometime you want to hide certain values by replacing them with NULL values. SQL Server offers you a nice function called NULLIF() to do this:

NULLIF(expression, value)

-- Returns NULL if "expression" equals to value"

-- Returns "expression", otherwise

NULLIF() can be viewed as the reverse function of ISNULL(). The tutorial script below shows you a good example of using NULLIF():

USE GlobalGuideLineDatabase;

GO

SELECT id, counts FROM ggl_links;

GO

id  counts

----------- -----------

101 NULL

102 8

1101 NULL

202 NULL

2101 NULL

2102 NULL

301 NULL

302 NULL

-- converting NULL to 0

UPDATE ggl_links SET counts=ISNULL(counts,0);

GO

 151 views

289⟩ What Is the Security Model Used in SQL Server 2005?

SQL Server 2005 uses a very standard security model involves 3 concepts:

* Securables - Entities representing resources that need to be secured. For example, a database table is a securable.

* Principals - Entities representing users that request accesses to resources. For example, a login user is a principal.

* Permissions - Types of accesses associated with securables. Permissions can be granted to or revoked from principals. For example, "Update" is a permission associated a securable, table "R". "Update" on "R" can be granted to a principal, user "U". Now user "U" will get "Update" access on table "R".

In simple terms, a principal answers the security question of "Who are you?"; a securable answers the security question of "What is your target object?"; a permission answers the security question of "You are allowed to perform this action on this target object".

SQL Server 2005 supports multiple securables and multiple principals organized into hierarchical structures.

 158 views

290⟩ What Are Security Principals Used in SQL Server 2005?

SQL Server 2005 supports several basic security principals located at different levels:

* Windows-Level Principals: Windows Local Login and Windows Network Domain Login - Used to control accesses to SQL Server instances.

* SQL Server-Level Principal: SQL Server Login. - Used to control accesses to SQL Server instances.

* Database-Level Principal: Database User. - Used to control accesses to database instances.

To access a SQL Server instance, you must use a Windows login or a SQL Server login previously created in that server instance. Once you logged in, you are represented by this login name as your security principal at the server level.

If you select a specific database in the server to use, SQL Server will search that database for a previously user that has been mapped to your login name. If that user is located, you are represented by this user name as your security principal at the database level.

 138 views

291⟩ What Is the Security Principal at the Server Level That Represents Your Session?

Security principal identifies who you are when you interact with the SQL Server. What can do you at the server level solely depends on the security principal that represents you. So it is very important to know your security principal at the server level.

What is the server level security principal of your session? The answer is simple - the login name you used to connect to the server to start the session. For example, if you connects to the server with the login name "sa", then your security principal is "sa" at the server level.

On a Unix system, there is a nice command called "whoami" which returns your security principal on the system. SQL Server provides a similar function called Suser_Sname(), which returns your security principal (a login name) at the server. Try it by following this tutorial example:

-- Find out your security principal at the server level

PRINT Suser_Sname();

GO

sa

This example shows you that you used "sa" as the login name to connect to the server.

 142 views

292⟩ What Is the Security Principal at the Database Level That Represents Your Session?

Security principal identifies who you are when you interact with the SQL Server. What can do you at the database solely depends on the security principal that represents you. So it is very important to know your security principal at the database level.

What is the database level security principal of your session? The answer is simple - the user name in the current database that has been mapped to your login name. For example, if you connects to the server with the login name "sa", and sets "GlobalGuideLineDatabase" as the current database, SQL Server will map "sa" to a user name defined in "GlobalGuideLineDatabase" based on some logics. That mapped user name is your security principal for "GlobalGuideLineDatabase" at the database level.

On a Unix system, there is a nice command called "whoami" which returns your security principal on the system. SQL Server provides a similar function called User_Name(), which returns your security principal (a user name mapped to the login name) at the database level. Try it by following this tutorial example:

PRINT Suser_Sname();

GO

sa

USE GlobalGuideLineDatabase;

GO

-- Find out your security principal at the database level

PRINT User_Name();

GO

dbo

This example shows you that "dbo" is user name in "GlobalGuideLineDatabase" that mapped to

 148 views

293⟩ How To Create a New Login Name in MS SQL Server?

In previous tutorials, it is assumed that you use the "sa" (System Administrator) login name to connect to your SQL Server. But that is not what a normal developer uses to connect to the server, since "sa" has the ALL permissions granted. You need to create new login names and grant less permissions to them, and give them to developers.

To create a new login name, you can use the "CREATE LOGIN" statement in a simple syntax like this:

CREATE LOGIN login_name WITH PASSWORD = 'password'

To run "CREATE LOGIN" statement, you need to connect to the server with a privileged login name like "sa". See the tutorial example below:

-- Login with 'sa'

-- Create new login names

CREATE LOGIN ggl_DBA WITH PASSWORD = 'ABD_LGG'

GO

Command(s) completed successfully.

CREATE LOGIN ggl_Login WITH PASSWORD = 'LGG'

GO

 145 views

294⟩ How To Verify a Login name with SQLCMD Tool?

The quickest way to verify a login name on a SQL Server is probably to use the SQLCMD tool, which takes the server name, login name and password in a single command line. Here is how to try it yourself:

Start a command window and enter the following command:

C:>SQLCMD -S LOCALHOSTSQLEXPRESS -U ggl_DBA -P ABD_LGG

1> PRINT Suser_Sname();

2> GO

ggl_DBA

1> QUIT

C:>

This shows ggl_DBA is a valid login and the password is correct. Now try this command:

C:>SQLCMD -S LOCALHOSTSQLEXPRESS -U ggl_DEV -P ABD_LGG

Msg 18456, Level 14, State 1, Server LOCALHOSTSQLEXPRESS, Line 1

Login failed for user 'ggl_DEV'.

C:>

This shows ggl_DEV is not a valid login or the password is incorrect.

 139 views

295⟩ How To List All Login Names on the MS SQL Server?

If you want to see a list of all login names defined on the server, you can use the system view, sys.server_principals as shown in this tutorial exercise:

-- Login with sa

SELECT name, sid, type, type_desc FROM sys.server_principals

WHERE type = 'S';

GO

name sid      type type_desc

-------- ----------------------------------- ---- ---------

sa 0x01 S SQL_LOGIN

ggl_DBA 0x348AF32B3B58CB40B67A5F5B7086B96E S SQL_LOGIN

ggl_Login 0x5EB8701EAEBAA74F86FCF5BD8E37B8C5 S SQL_LOGIN

So you have two login names on the server at this moment.

 140 views

296⟩ How To Change a Login Name in MS SQL Server?

If you want to change a login name, you can use the "ALTER LOGIN" statement as shown in this tutorial example:

-- Login with "sa"

-- Change login name

ALTER LOGIN ggl_Login WITH NAME = Dba_Login;

GO

-- View login names

SELECT name, sid, type, type_desc FROM sys.server_principals

WHERE type = 'S';

GO

name sid      type type_desc

-------- ----------------------------------- ---- ---------

sa 0x01 S SQL_LOGIN

ggl_DBA 0x348AF32B3B58CB40B67A5F5B7086B96E S SQL_LOGIN

Dba_Login 0x5EB8701EAEBAA74F86FCF5BD8E37B8C5 S SQL_LOGIN

 146 views

297⟩ How To Change the Password of a Login Name in MS SQL Server?

If a developer lost the password of his or her login name, you can reset the password with the "ALTER LOGIN" statement as shown in this tutorial example:

-- Login with sa

ALTER LOGIN ggl_DBA WITH PASSWORD = 'globalguideline';

GO

Command(s) completed successfully.

ggl_DBA's password is changed now. Try it with the SQLCMD tool:

C:>SQLCMD -S LOCALHOSTSQLEXPRESS -U ggl_DBA -P globalguideline

1> QUIT

You can also use the "ALTER LOGIN" to change your own password.

 135 views

298⟩ How To Disable a Login Name in MS SQL Server?

If you want temporarily disable a login name, you can use the "ALTER LOGIN" statement with a DISABLE keyword. If you want to enable it later on, you can use the ENABLE keyword. The tutorial exercise below shows how to disable and enable login name "Dba_Login":

-- Login with "sa"

-- Disable a login

ALTER LOGIN ggl_Login DISABLE;

-- View login status

SELECT name, type, type_desc, is_disabled

FROM sys.server_principals

WHERE type = 'S';

GO

name type type_desc is_disabled

----------- ---- ---------- -----------

sa S SQL_LOGIN 0

ggl_DBA S SQL_LOGIN 0

Dba_Login S SQL_LOGIN 1

Now try to login with the disabled login name:

C:>SQLCMD -S LOCALHOSTSQLEXPRESS -U Dba_Login -P IYF

Msg 18470, Level 14, State 1, Server LOCALHOSTSQLEXPRESS

Login failed for user 'Dba_Login'. Reason: The account is

disabled.

C:>

Run the statements below to enable login name "Dba_Login":

-- Login with "sa"

-- Enable a login

ALTER LOGIN ggl_Login ENABLE;

 152 views

299⟩ How To Delete a Login Name in MS SQL Server?

If you don't want to keep a login name any more, you should delete it by using the "DROP LOGIN" statement as shown in this tutorial example:

-- Login with "sa"

DROP LOGIN Dba_Login;

GO

Command(s) completed successfully.

-- View login names

SELECT name, sid, type, type_desc FROM sys.server_principals

WHERE type = 'S';

GO

name sid      type type_desc

-------- ----------------------------------- ---- ---------

sa 0x01 S SQL_LOGIN

ggl_DBA 0x348AF32B3B58CB40B67A5F5B7086B96E S SQL_LOGIN

 137 views

300⟩ How To Create a User Name in a Database?

User names are security principals at the database level. If you want to allow a login name to access a specific database, you need to create a user name in that database and link it to the login name.

Creating a user name can be done by using the "CREATE USER" statement as shown in this tutorial exercise:

-- Login with "sa"

-- Create a login

CREATE LOGIN ggl_Login WITH PASSWORD = 'IYF'

GO

-- Select a database

USE GlobalGuideLineDatabase;

GO

-- Create a user and link it to a login

CREATE USER ggl_User FOR LOGIN ggl_Login;

GO

Login name "ggl_Login" should be able to access database "GlobalGuideLineDatabase" through user name "ggl_User".

 139 views