In this blog we will see how to handle errors in SQL server.
We use try catch blocks just like C#. In this example we
will try to divide a number by Zero and let us see how the error message is
displayed. When the error comes it goes to catch block.
Write the below script in SQL Server
BEGIN TRY
DECLARE @number INT
SET @number = 2/0
PRINT 'This will not execute'
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO
When we run this script we get the following output.

In this Article we will see how to insert values in a table with just an identity column.
When we make an identity column in a table then for every record inserted in the table the identity column auto increments the value without specifying the identity column in the Insert command. What if we have to insert record in this column manually using a SQL command? So in this article we will just see how to achieve this.
We will create a table with just an identity column. Once the table is created we will try to insert records in this table using SQL query.
Write the following script in SQL Server to create a table.
Create table tblInsertintoIdentityColumn ( Id int primary key identity ) |
Execute the above SQL code to create a table in the selected database. Execute the following query to check the contents in the table. As we haven’t inserted any records in this table, so the query will just return the table’s schema.
Select * from tblInsertintoIdentityColumn
|

Now we will insert value in this table. Write the following query.
Insert into tblInsertintoIdentityColumn default values |
|

As we can see the command is successfully executed. So let us check the records in the table.
Run a select query and check the records in the table.

And so on we can insert as many records in the Identity column in a table.
No comments:
Post a Comment