Feeds:
Posts
Comments

Posts Tagged ‘SQL Server’

In my last article, I shared how to calculate Future Value of Annuity(FV) function in SQL Server and as promised in this article, today I will be sharing about Present Value of Annuity(PV) function in SQL Server, another important financial function.

Given below is the script of Present Value of Annuity function in SQL with examples :

CREATE FUNCTION UDF_PresentValue
(@InterestRate NUMERIC(18,8), --Rate is the interest rate per period.
@Nper          INT,           --Nper is the total number of payment
--periods in an annuity.
@Pmt           NUMERIC(18,4), --Pmt is the payment made each period;
--it cannot change over the life
--of the annuity.PaymentValue must be
--entered as a negative number.
@Fv            NUMERIC(18,4), --Fv is the future value, or the lump-sum
--amount that a series of future payments
--is worth right now. If Fv is omitted,
--it is assumed to be 0 (zero).
--FV must be entered as a negative number.
@Type		   BIT            --Type is the number 0 or 1 and indicates
--when payments are due.
--If type is omitted, it is assumed to be 0
-- which represents at the end of the period.
--If payments are due at the beginning
--of the period, type should be 1.
)
RETURNS NUMERIC(18,2) --float
AS
BEGIN
DECLARE  @Value NUMERIC(18,2)
SELECT @Value =
Case WHEN @Type=0
THEN @Pmt*(Power(Convert(float,(1 + @InterestRate / 100)),@Nper)
-1) /(((@InterestRate / 100))
* Power((Convert(float,1 + @InterestRate / 100)),@Nper))
+ @Fv *
Power(Convert(float,(1 + @InterestRate / 100)),@Nper)

WHEN @Type=1
THEN @Pmt*(Power(Convert(float,(1 + @InterestRate / 100)),@Nper)
-1) /(((@InterestRate / 100))
* Power((Convert(float,1 + @InterestRate / 100)),@Nper))
* (1 + @InterestRate / 100)
+ @Fv
* Power(Convert(float,(1 + @InterestRate / 100)),@Nper)
END
RETURN @Value*-1
END
GO
--Syntax
--dbo.UDF_PresentValue(@InterestRate,@Nper,@Pmt,@Fv ,@Type)
--You can find the same syntax in excel.
--PV(Rate,Nper,Pmt,Fv ,Type)

SELECT dbo.UDF_PresentValue(0.625,24,250,0,0)
---5555.61						--SQL OUTPUT
--=PV(7.5%/12, 2*12, 250,0, 0)	--EXCEL FORMULA
--($5,555.61)					--EXCEL OUTPUT
GO

SELECT dbo.UDF_PresentValue(0.1153846,208,50,0,1)
---9252.07						--SQL OUTPUT
--==PV(6%/52, 4*52, 50, , 1)	--EXCEL FORMULA
--($9,252.07)					--EXCEL OUTPUT
GO
SELECT dbo.UDF_PresentValue(5.25,10,100,0,0)
---762.88						--SQL OUTPUT
--=PV(5.25%/1, 10*1, 100, , 0)	--EXCEL FORMULA
--($762.88)					    --EXCEL OUTPUT
GO

Appreciate your valuable feedback about this function.

Reference : Castle
Techonthenet

Read Full Post »

Whenever I used to work on financial reports, I used to grab the data from SQL Server and do it on Excel 2007/ 2010. The reason behind this is Excel has very strong financial functions. I tried to develop these financial functions in SQL with the same parameters like Excel, so the developers using Excel can do these financial reports in SQL.

Given below is the Future Value of Annuity function in SQL :

Create FUNCTION UDF_FutureValue
(@InterestRate NUMERIC(18,8), --Rate is the interest rate per period.
@Nper INT                 ,  --Nper is the total number of payment periods in an
--annuity.
@Pmt  NUMERIC(18,4)       ,  --Pmt is the payment made each period; it cannot
--change over the life of the annuity.
--Payment Value must be entered as a negative
--number.
@Pv   NUMERIC(18,4)       ,  --Pv is the present value, or the lump-sum amount
--that a series of future payments is worth right
--now. If Pv is omitted, it is assumed to be 0
--(zero). PV must be entered as a negative number.
@Type  BIT                    --Type is the number 0 or 1 and indicates when
--payments are due.
--If type is omitted, it is assumed to be 0
--which represents at the end of the period.
--If payments are due at the beginning of
--the period, type should be 1.
) RETURNS NUMERIC(18,2)
AS
BEGIN
DECLARE  @Value NUMERIC(18,2)
SELECT @Value =
Case WHEN @Type=0 THEN
@Pmt* ((Power(Convert(float,(1 + @InterestRate / 100)),@Nper)-1)
/Convert(float,(@InterestRate / 100)))
+ @Pv * Power((1 + @InterestRate / 100),@Nper)

WHEN @Type=1 THEN
@Pmt*((Power(Convert(float,(1 + @InterestRate / 100)),@Nper)-1)
/Convert(float,(@InterestRate / 100))) *
Convert(float,(1 + @InterestRate / 100))+ @Pv *
Power(Convert(float,(1 + @InterestRate / 100)),@Nper)
END
RETURN @Value*-1
END
GO
--Syntax
--dbo.UDF_FutureValue(@InterestRate,@Nper,@Pmt,@Pv ,@Type)
--You can find the same syntax in excel.
--FV(Rate,Nper,Pmt,Pv ,Type)

SELECT dbo.UDF_FutureValue(0.625,24,-250,-5000,0)
--12258.14                           --SQL OUTPUT
--=FV(7.5%/12, 2*12, -250, -5000, 0) --EXCEL FORMULA
--$12,258.14                         --EXCEL OUTPUT
GO
SELECT dbo.UDF_FutureValue(6,30,0,-5000,1)
--28717.46                          --SQL OUTPUT
--=FV(0.06,30,0,-5000,1)            --EXCEL FORMULA
--$28,717.46                        --EXCEL OUTPUT
GO
SELECT dbo.UDF_FutureValue(6,30,-1200,0,1)
--100562.01                      --SQL OUTPUT
--=FV(0.06,30,-1200,0,1)         --EXCEL FORMULA
--$100,562.01                    --EXCEL OUTPUT
GO
SELECT dbo.UDF_FutureValue(6,30,-1200,-5000,1)
--129279.47                     --SQL OUTPUT
--=FV(0.06,30,-1200,-5000,1)    --EXCEL FORMULA
--$129,279.47                   --EXCEL OUTPUT
GO
SELECT dbo.UDF_FutureValue(0.50,360,-100,0,1)
--100953.76                     --SQL OUTPUT
--=FV(0.06/12,360,-100,0,1)     --EXCEL FORMULA
--$100,953.76                   --EXCEL OUTPUT

Let me know your valuable feedback about this function. Shall post Present Value of Annuity in the coming post.

Reference : Castle
Techonthenet

Read Full Post »

I received a request to add a column in the entire table of the database for a customer. It was so simple that I made the script as given below and told them to run it first and then again run its result set in SQL server, so all tables would be altered. It appeared that the Job was done but unfortunately it was not. One thing I forgot to mention is that the client environment in SQL Server 2012. If you look at the query it will perform alter table in all user table.

Select 'Alter Table ' + quotename(schema_name([schema_id])) +'.' + quotename([name])
+ ' ADD [GUID] uniqueidentifier default newid()' from sys.tables

filetableidentify1.1

Ooops… it generated an error.

Msg 33422, Level 16, State 1, Line 4
The column ‘GUID’ cannot be added to table ‘dbo.DataBank’ as it is a FileTable.
Adding columns to the fixed schema of a FileTable object is not permitted.
filetableidentify1.2

The reason behind this error is that I made an alter statement for even the File Table, while you cannot add any column in the File Table.

I, therefore, need to remove the file table from the query result set. So I did a little research and found that if you use the column is_filetable (data type bit) in sys.tables, you can easily identify whether it as a file table  or not . If is_filetable  is 1, then the table is a File Table else not.
So, I changed the query and it worked perfectly. Now you can see that the query will only generate the script for normal table (not file tables).

Select 'Alter Table ' + quotename(schema_name([schema_id])) +'.' + quotename([name])
+ ' ADD [GUID] uniqueidentifier default newid()' from sys.tables where is_filetable =0

filetableidentify1.3

Let me know if you know other ways to find file table as well.

Read Full Post »

In my previous post, I discussed how we could apply different Data Definition Language (DDL) Statements on File Table. Today, we will discuss how to apply Data Manipulation Language (DML) Statements on a File Table.

  • Insert record in File Table :

There are two ways to do it.

  1. Via SQL Server Management Studio (GUI)
  2. Via Transact SQL

1-Via SQL Server Management Studio (GUI)
This is the simplest way of insertion of any record in the File Table.
Lets do it step by step :

Step 1:
First copy the file that you want to place in the file table. For example abc.txt (text file).

Step 2:
Then go to the database, where you have created a file table and then select the file table and right click on it.

filetable3.1.1
Step 3:
Click on the Explore File Table Directory

Step 4:
It will open the directory pointing to this file table. Just paste the file (abc.txt) in it.
filetable3.1.2

Step 5:
After that just execute the select statement to verify whether the file is there or not.

Use MyFileTableDB
GO
select * from databank

filetable3.1.3

2-Via Transact SQL

Given below is the method to insert data into file table. But make sure the file is more than 0 KB.

INSERT INTO [dbo].[databank] ([name],[file_stream])
SELECT'Test file',
* FROM OPENROWSET(BULK N'C:\abc-2.txt', SINGLE_BLOB) AS FileData
GO
  • Select records from File Table :

The select statement of a file table is same like a normal table. Given below is the script to browse file table :

Select * from dbo.DataBank

filetable2.1.4

  • Update records in File Table :

Given below is the script to update file table.

Update Databank set [name]='test file-2' where [name]='test file'

Once you update the file table and change the name of the file, execute the select statement to verify whether the update is successfully done or not.

Select * from dbo.DataBank

filetable2.1.5

  • Delete records in File Table :

Given below is the script to delete files from the file table. Make sure you select the correct file name, because it will not only delete record from the file table but also physically delete the file from the directory as well.

Delete from DataBank where [name]='test file-2'

Once you delete the file from file table, execute the select statement to verify whether the delete is successfully done or not.

Select * from dbo.DataBank

filetable2.1.6

Read Full Post »

In my previous article, we discussed about how to enable FileStream and File table in SQL Server 2012. Today, we will learn how to perform Data Definition Language (DDL) Statements in file table.

  • Create File table :

Given below is the script to create file table :

USE MyFileTableDB
GO
CREATE TABLE DataBank AS FileTable
WITH (
FileTable_Directory = 'MyFileTable_Dir'
);

Once file table is created successfully, you can execute given below script to check whether the file table is created or not.

select * from sys.filetables where object_id=object_ID('databank')

filetable2.1.1

  • Alter File table:

In the above file table, I wrongly spelled the FileTable_Directory name. So, can we alter file table and correct FileTable_Directory name?
Given below is the script to alter file table.

ALTER TABLE DataBank SET ( FILETABLE_DIRECTORY = N'MyFileTable_Directory');

Once file table is altered, you can execute the given below script to verify.

select * from sys.filetables where object_id=object_ID('databank')

filetable2.1.2

  • Truncate File table:

If you want to truncate the file table, given below is the script but it will delete all data files in the file table (be careful).

TRUNCATE TABLE databank
  • Drop File table:

If you want to drop the file table, given below is the script but it will also drop all the data files associated with this files table (be careful).

DROP TABLE databank

Tomorrow I shall post how to perform Data Manipulation Language (DML) Statements to file table.

Read Full Post »

File table is one of the excellent features introduced in SQL Server 2012. This feature provides the compatibility between windows application and file data stored in SQL Server and gives the support of windows file names space (Windows API) as well. In simple words you can say, from File table you can handle windows files and directories via SQL server 2012. This nice feature is a build on top of file stream technology. In other words, you must enable file stream to use File Table.

In this article, we will learn how to enable File Stream and create File Table in sql server.

Let’s do it step by step to view how it works.

Step 1: Enable File Stream in SQL server 2012:
There are 2 ways to enable file stream in SQL server 2012.

  1. Via T-SQL
  2. Via Configuration Manager

1- Via T-SQL
Given below is the script to enable file stream in SQL server 2012. Execute the given below code and don’t forget to restart the SQL Server Service.

EXEC sp_configure filestream_access_level, 2
RECONFIGURE

2- Via Configuration Manager
Through configuration manager, we need to follow certain steps to enable file stream in sql server:
Step I
Open SQL Server configuration Manager.
Step II
Then locate the sql server instance on which, you need to enable file stream on it.
Step III
Then select the instance and right click on it and select properties.
Enablefilestream1.1
Step IV
Select Filestream Tab and Enable FILESTREM for transact SQL access and give windows share name as well. By default it is instance name. If remote users need the access of file stream then you should also allow remote client access to file stream data.
Enablefilestream1.2
Step V
Click apply

Step 2: Create File table enabled Database in SQL server 2012:
There are 2 ways to create file table enabled database in SQL server 2012.

  1. Via T-SQL
  2. Via SSMS GUI Interface

1- Via T-SQL
Execute the given below script to create a file table enabled database.

CREATE DATABASE [MyFileTableDB]
ON PRIMARY
( NAME = N'MyFileTableDB', FILENAME = N'C:\DATA\MyFileTableDB.mdf'),
FILEGROUP MyFileGroup CONTAINS FILESTREAM (NAME = MyFileTableFS,FILENAME='C:\Data\MyFileTable')
LOG ON
( NAME = N'MyFileTableDB_log', FILENAME = N'C:\DATA\MyFileTableDB_log.ldf')
WITH FILESTREAM ( NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'MyFileTableDB' )
GO

2- Via SSMS GUI Interface
Right click on the databases and create a new database in SSMS and enter all the information required to create a simple database, then go to options and set two properties.

  •   Enter FILESTREAM Directory name = MyFileTableDB
  •   Make FILESTEAM Non-Transacted Access = FULL

Enablefilestream1.3

Lets check that file table enabled database is whether created or not.

SELECT DB_NAME(database_id) as [Database Name],
non_transacted_access,
non_transacted_access_desc
,directory_name
FROM sys.database_filestream_options

Enablefilestream1.4

Step 2.1: Enable a file table in an existing Database in SQL server 2012:
There are 2 ways to enable file table in an existing database in SQL server 2012.

  1. Via T-SQL
  2. Via SSMS GUI Interface

1- Via T-SQL
Execute the given below script to enable a file table in an existing database.

ALTER DATABASE test
SET FILESTREAM ( NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'testfiletable' )
GO

2- Via SSMS GUI Interface
Right click on the databases goto options and set two properties.

  • Enter FILESTREAM Directory name = MyFileTableDB
  • Make FILESTEAM Non-Transacted Access = FULL

Enablefilestream1.3

Will discuss another nice features of file table in up coming posts.

Read Full Post »

sp_describe_undeclared_parameters is one of the featured system stored procedures introduced in SQL Server 2012. In this article we will discuss this stored procedure syntax, purpose & examples.

Syntax:

sp_describe_undeclared_parameters
[ @tsql = ] 'Transact-SQL_batch'
[ , [ @params = ] N'parameters' data type ] [, ...n]

Purpose :
This function gives us details about all undeclared parameters of any t-sql query. Lets say if I give you a dynamic sql and tell you to execute it. You will definitely ask me two main questions :

  • How many parameters are required to execute this dynamic sql ?
  • What are the data types of these parameters ?

Without having answers to above questions you cannot execute a dynamic t-sql query ? The beauty of sp_describe_undeclared_parameters stored procedure is, it will give you the answers to above questions and once you have the parameters & its data type, you can easily execute any dynamic sql.

Lets do it step by step.

Step 1 :
In the given below example, we have a t-sql but we don’t know how many parameters are required and its data type, nevertheless we will try to execute it.

Use AdventureWorks2012
GO
DECLARE @SQL NVARCHAR(500);
DECLARE @ParameterDefinition NVARCHAR(500);
DECLARE @BusinessEntityID INT;

SET @SQL =N'SELECT @BusinessID=[BusinessEntityID] from [HumanResources].[vEmployee]
Where [FirstName]=@FName';

EXECUTE sp_executesql @SQL
--OUTPUT

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable “@BusinessID

Oops ! error because we did not pass the parameters and we don’t know about it either.

Step 2 :
Lets pass the same t-sql to sp_describe_undeclared_parameters to get parameters details including segregation of input and output parameters.

sp_describe_undeclared_parameters @tSQL=N'SELECT @BusinessID=[BusinessEntityID]
from [HumanResources].[vEmployee] Where [FirstName]=@FName';

undeclared_parameters1.1

Step 3 :
Now, you have the parameters details including which one is input and output parameter. Lets pass it and view the results.

Example-1 :

use AdventureWorks2012
GO
DECLARE @SQL NVARCHAR(500);
DECLARE @ParameterDefinition NVARCHAR(500);
DECLARE @BusinessEntityID INT;
DECLARE @FirstName as NVARCHAR(50)

SET @FirstName='Ken'
SET @SQL =N'SELECT @BusinessID=[BusinessEntityID] from [HumanResources].[vEmployee]
Where [FirstName]=@FName';

SET @ParameterDefinition = N'@FName nvarchar(50), @BusinessID INT OUTPUT';

EXECUTE sp_executesql @SQL
,@ParameterDefinition,
@FName=@FirstName,
@BusinessID =@BusinessEntityID OUTPUT;

SELECT @BusinessEntityID as [BusinessEntityID]
GO
--OUTPUT

BusinessEntityID
———————
1
(1 row(s) affected)

Example-2 :
In this example we know only one parameter and the rest of the parameters we don’t. Simply we need to pass t-sql and the known parameter to sp_describe_undeclared_parameters, and it will give you the unknown / undeclared parameter information.

sp_describe_undeclared_parameters @tSQL=N'SELECT @BusinessID=[BusinessEntityID]
from [HumanResources].[vEmployee] Where [FirstName]=@FName'
,@params =N'@FName nvarchar(50)'
--OUTPUT

undeclared_parameters1.2

Example-3 :
Sometimes, we know all the parameters but to make sure none of the parameters is missing, simply we need to pass t-sql and the all parameters to sp_describe_undeclared_parameters, it will give you the  missing parameters (if any), otherwise Nil result set.

sp_describe_undeclared_parameters @tSQL=
N'SELECT @BusinessID=[BusinessEntityID]
from [HumanResources].[vEmployee] Where [FirstName]=@FName'
,@params =N'@FName nvarchar(50), @BusinessID INT OUTPUT'

undeclared_parameters1.3

Will post some real world examples in the upcoming posts.

Read Full Post »

In my previous article, I wrote about Executing Stored Procedure with Result Sets. I utilized this new feature introduced in SQL Server 2012 many times and it is very handy, when it comes to manipulate stored procedure result sets.

Today, I was reading a question related to this topic in a forum where a community member tried to manipulate stored procedure result set with result sets keyword and then insert it into a temporary table. But it gives an error.

Let me create few examples to explain the problem :

Example 1 :
In this example, we will insert the result set of a stored procedure in a temporary table without using result set keyword and it works fine.

Use AdventureWorks2012
GO
Create Table #temp
(
[DepartmentID] int,
[Name] varchar(50)
)
GO
Create PROCEDURE SP_ResultSet_Example1
as
Select [DepartmentID]
,[Name]
from [HumanResources].[Department]
GO
Insert into #temp EXEC SP_ResultSet_Example1
GO
Select * from #temp order by [DepartmentID]

resultseterror1.1

Example 2 :
In this example, we will insert the result set of a stored procedure in a temporary table with result sets keyword. It gives an error .

Use AdventureWorks2012
GO
Create Table #temp
(
[DepartmentID] int,
[Name] varchar(50)
)
GO
Create PROCEDURE SP_ResultSet_Example1
as
Select [DepartmentID]
,[Name]
from [HumanResources].[Department]
GO

Insert into #temp EXEC SP_ResultSet_Example1 WITH RESULT SETS
(
([Department ID] int NOT NULL,
[Department name] Name NOT NULL));
GO
Select * from #temp order by [DepartmentID]

resultseterror1.2

Explanation :
We cannot use result sets keyword, when we need to insert any stored procedure result set into a table. The reason behind this is if we use result sets keyword we can return multiple results with different columns and with different data types from a single stored procedure and this functionality cannot be handled in a single table. As per MSDN ” WITH
Possible execute options. The RESULT SETS options cannot be specified in an INSERT…EXEC statement.”
.

Read Full Post »

I received a query from one of the community members, before discussing his query I would like to discuss his environment first. He is working in an environment where multiple users shares the same machines and the same credentials to work on SQL Server Management Studio 2005. He asked me, if I could help him to remove the recent files activity from the menu, to restrict any other user from viewing his activities.

Given below is the screen image in SQL server 2005 with the recent files history.

Recent activity 1.2

I started searching the solution in SSMS and found few solutions :

Solution 1
You need to go to Tools \ Options \ Environment \ General
Here you can change the display files in recently used list from 10 (By default it is 10) to 1.
There are two issues with this solution :

  • You cannot make it 0.
  • If you make it 10 again, it will show you the history again.

Recent activity 1.1

Solution 2
You can delete the recent file activity history through registry. Open the registry via “regedit.exe” and go to the given below path with respect to the SQL Server version you are using and delete the key related to your files as shown in below image.
SQL SERVER 2005
HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\90\Tools\Shell\FileMRUList

SQL SERVER 2008
HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\100\Tools\Shell\FileMRUList

SQL Server 2012
HKEY_CURRENT_USER\Software\Microsoft\SQL Server Management Studio\11.0\FileMRUList

Recent activity 1.3

After that close the SSMS and open it again, there will be no recent files activities.

Recent activity 1.4

Let me know if you know a better solution.

Read Full Post »

sys.dm_exec_query_stats is very helpful dynamic management view when it comes to query recovery.
Sometimes we write queries to perform some operations in the database and after that close the script window without saving. Later on realize, if only had I saved it, it would have saved some time. Here the solution comes namely sys.dm_exec_query_stats.
This view can recover your query from sql server. Let me create an example to explain it.

First open a new query window and execute the given below script and close the query without saving it.

USE AdventureWorks2012
GO
Select * from Sales.vStoreWithContacts
Select * from Production.ScrapReason
Select * from Sales.vStoreWithAddresses
Select * from Purchasing.vVendorWithContacts
Select * from HumanResources.Shift
Select * from Purchasing.vVendorWithAddresses
Select * from Production.ProductCategory
Select * from Purchasing.ShipMethod
Select * from Production.ProductCostHistory
Select * from Production.ProductDescription
Select * from Sales.ShoppingCartItem

After that, just execute the given below script, it will recover your query.

SELECT Distinct qt.TEXT AS [Queries]
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt

dm_exec_query_stats1.1

The reason why we used distinct in the above query is, there are queries that we have executed multiple times that will appear as well.

Still, I am searching for a solution that can link these queries to the user who executed it so the recovery would be easier. Will update you on this in the upcoming post.

Reference : MSDN

Read Full Post »

« Newer Posts - Older Posts »