In the post, we learn about creating and calling inline table-valued functions. Where do we use inline table-valued functions? now Before continuing with the session, I strongly recommend reading this post.
In the post, we have discussed how to create and call scalar user-defined functions.
In this part, we learn about the inline table value functions. We know that a scalar function returns a scalar value as a single value, whereas an inline table-valued function returns a table.
Now let’s look at an example of creating an inline table-valued function.
if you look at this, I’ve got a TblUsers table we just got I’d name, Email, Password, Gender, DOB, and ContactNo columns. Now I want you to write a function that can give me the output that you can see in the below image.
The function should return users by gender. For example, if I passed in function gender as male, I want only the male users to be returned and along the same lines If I pass the gender as female and I only want the female users to be returned.
How to create and call inline table-valued function
To do that we use the create function statement as we have used it to create scalar function.
The syntax for creating an inline table-valued function
CREATE FUNCTION Your_Function_Name(@Parameter1 DataType, @Parameter2 DataType..., @Parametern DataType)
RETURNS TABLE
AS
RETURN (Select_query_Statement)
Inline table-valued function Example
CREATE FUNCTION [dbo].[UsersByGender](@UserGender nvarchar(10))
RETURNS TABLE
AS
RETURN (Select Id, Name,Email, DOB, Gender, ContactNo
from TblUsers
where Gender = @UserGender)
so let’s execute this. when I execute command completed successfully.so where did this function get created? once I expand the database, go to programmability and then functions there,You should see inline table-valued functions. So that gets stored in this table-valued functions folder.If you can’t see that, just refresh it and expand the plus sign.
if you look at the implementation of the function here, it’s very simple to understand.So we use the create function statements so create function function_name and UsersByGender is the name of the function because we are going to return users by gender.
And if you look at function, obviously this function needs a parameter @UserGender of type nvarchar.since gender is a string we use nvarchar data type, and then this function returns table. so this is the parameter that we are passing into this function and this function returns table.
how to call inline table valued function
Now, let us see how to call this function, so obviously, to call this function, you know, we use the syntax select * from the function_name and then pass whatever parameters you have to pass to that function.
Now, this function returns the table, so treat it as it is a table. now if we want to select from a table, we will select * from that table_name.
Similarly, this is an inline table-valued function just issue a select statement against the inline table value function as if you would issue a statement against a table. So select * from that function_name.
select * from DemoDataBase.dbo.UsersByGender('Male')
I want all the male users so I am passing in male and when we execute this query we only get the male users back and along the same lines.
If I want female users I just pass female and execute the query so I only get the female users.that’s the syntax that we use to execute. I mean to call the function.Now if you want, you can use the where clause
select * from DemoDataBase.dbo.UsersByGender('Male') where name='Ammy'
As we know scalar function returns a scalar data type, for example, maybe nvarchar or integer or daytime, a scalar value. But we want this function to return a list of employees by gender.
so obviously we want this function to return a table. So we are specifying table as the return type from this function using the returns Keywood and then we are using AS keyword and return.
Look at the inline table-valued function. We are not using the Begin and END block.
If you remember for the scalar user-defined function we had Begin and END block, the function body was enclosed within that block, but for an inline table-valued function, it’s a compile-time error to have the Begin and END block. You cannot have it for an inline table value function.
CREATE FUNCTION [dbo].[UsersByGender](@UserGender nvarchar(10))
RETURNS TABLE
AS
RETURN (Select Id, Name,Email, DOB, Gender, ContactNo
from TblUsers
where Gender = @UserGender)
So immediately after the AS keyword, you specify the return and within brackets, you specify your select statement.
so what do we want here? We want Id, name, Email, DOB, gender, and ContactNo columns, so specify them in your select list from TblUsers table where gender equals @UserGender parameter, whatever the user is going to pass in.
so we are using that parameter there and we are inclosing that entire select statement in parentheses.
I mean even if you don’t indicate that we don’t get an error but it is more readable now after whatever is present in the parentheses is completed return the output of the execution result of the select statement back to the calling application.
Comparison of inline table-valued functions with scalar, user-defined functions
So when somebody calls your function, return whatever your select statement is selecting here. OK, so if you notice, there are three points to keep in mind when we compare inline table-valued functions with scalar, user-defined functions.
In inline table-valued functions, we specify the table as the return type, whereas for scalar functions we specify any of the scalar data types like Integer and nvarchar.For scalar functions, the function body is not enclosed between begin and end block.
The structure of the table, it is very important. Now, look at this. You are telling your function it’s going to return a table. But what are the columns that are going to be present in that table? You know, basically the structure of the table.
We are not defining that here.so the structure of the table will be determined by the select statement that you have.
So obviously the table that this function is going to return is going to have five columns because your select query has five columns within it Select list.
so the structure of the table that gets returned is determined by the select statement within the function body, but later in the next session, we’ll be talking about multi-statement table-valued function there we have the luxury of specifying the structure of the table after the return key.we will talk about that in the next post.
Use of inline table-valued function
So where can we actually use this inline table-valued function. Inline-table value functions can be used to achieve the functionality of parametrized views
Now, what is a view, and what are parametrized views? Read Below Post
But just keep in mind that inline table-valued functions are an exceptional replacement for parametrized views.
you can actually use it in Join as well. we know that the inline table-valued function returns a table. So the table returned by the table-valued function can be used in joins with other tables.
Table Script
CREATE TABLE [dbo].[TblUsers1](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Email] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NULL,
[Gender] [nvarchar](50) NOT NULL,
[CreatedAt] [datetime2](7) NOT NULL,
[DOB] [datetime2](7) NOT NULL,
[ContactNo] [nvarchar](max) NULL,
)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2, 'rajat Saxena', 'rajat.nirmal@gmail.com', 'BcpDvZOpQXnBkIihOB3y7A%3d%3d', 'Male', CAST('2019-11-17T16:56:35.8000000' AS DateTime2), CAST('1996-04-22T15:58:28.9210849' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (3, 'Pankaj Patel', 'Pankaj@gmail.com', 'te9LBxguCUJFRbqSWozghg%3d%3d', 'Female', CAST('0001-01-01T00:00:00.0000000' AS DateTime2), CAST('2000-12-05T13:25:01.9770780' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (1003, 'Ammy', 'pankajabc@gmail.com', 'BiYuRVMYd1Ue8iKoE%2bA2WA%3d%3d', 'Male', CAST('0001-01-01T00:00:00.0000000' AS DateTime2), CAST('1992-12-23T13:43:27.5816869' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (1004, 'Test 2', 'pankajabcd@gmail.com', 'BiYuRVMYd1Ue8iKoE%2bA2WA%3d%3d', 'Female', CAST('0001-01-01T00:00:00.0000000' AS DateTime2), CAST('1995-12-05T05:19:23.3650433' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (1005, 'Mark', 'test@test.com', 'te9LBxguCUJFRbqSWozghg%3d%3d', 'Male', CAST('0001-01-01T00:00:00.0000000' AS DateTime2), CAST('2020-06-04T12:29:28.7768304' AS DateTime2), '0987654321')
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (1006, 'Priya', 'test1@test.com', 'te9LBxguCUJFRbqSWozghg%3d%3d', 'Female', CAST('0001-01-01T00:00:00.0000000' AS DateTime2), CAST('2019-12-05T05:22:11.8963884' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2004, 'Jonii', 'pankajws@gmail.com', 'BiYuRVMYd1Ue8iKoE%2bA2WA%3d%3d', 'Female', CAST('2019-11-25T11:29:06.9385410' AS DateTime2), CAST('2019-12-05T05:20:30.6045240' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2005, 'Jinny', 'pankajadequate@gmail.com', 'erxz7AefO88uggAc3kkx69Y5Sa1fOb4UBfCWJ8PNqWQ%3d', 'Female', CAST('2019-11-25T13:12:47.6690112' AS DateTime2), CAST('2019-12-05T05:20:34.2935856' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2006, 'Hr. Niels Henriksen', 'contact@adequateinfosoft.com', 'Ih2xENnNQbBnjv07ia4QFQ%3d%3d', 'Male', CAST('2019-11-26T05:58:34.8949750' AS DateTime2), CAST('2019-12-05T05:20:37.5393081' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2007, 'Neeraj Singh', 'neirajsingh101@gmail.com', 'SoIF2JssyCvePj9JyjNTXASEltv9VsXDIqxw4MQvkUw%3d', 'Male', CAST('2019-11-26T12:42:18.6778716' AS DateTime2), CAST('2019-12-05T05:20:40.9827126' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2008, 'Test 8', 'test3@test.com', 'te9LBxguCUJFRbqSWozghg%3d%3d', 'Female', CAST('2019-11-27T10:09:42.6969868' AS DateTime2), CAST('2019-11-27T10:09:42.6969869' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2009, 'Test 9', 'test10@gmail.com', 'te9LBxguCUJFRbqSWozghg%3d%3d', 'Female', CAST('2019-11-27T10:20:10.5816545' AS DateTime2), CAST('2019-11-27T10:20:10.5816545' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2010, 'Test 10', 'test02@gmail.com', 'te9LBxguCUJFRbqSWozghg%3d%3d', 'Female', CAST('2019-11-27T10:41:07.8215121' AS DateTime2), CAST('2019-11-27T10:41:07.8215122' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2011, 'Aankashi', 'alokpatel@gmail.com', '0SM6YcqEHZq29W%2fFPtcLQw%3d%3d', 'Male', CAST('2019-11-30T05:36:52.1332523' AS DateTime2), CAST('2019-12-05T05:21:49.0948144' AS DateTime2), NULL)
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Password], [Gender], [CreatedAt], [DOB], [ContactNo]) VALUES (2012, 'Aakankshi Gupta', 'aakankshi@gmail.com', 'kUEOh62X7XbOIEqBtV0FDQ%3d%3d', '0', CAST('2019-12-05T04:35:42.6189131' AS DateTime2), CAST('2019-12-05T04:35:42.6189131' AS DateTime2), NULL)
GO
The post How to create Inline table-valued functions in SQL server appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- SQL 2008 Linked Server Connection
- SQL Server view for calc ParentId column
- Sum two column values together in SQL
- Looking for the best way to return pass in a parameter to allow me to return a specific customer or all customers in SQL
- How parse Sql Script with dapper? (SET PARSEONLY ON + Dapper)
- Error While Executing my Stored Procedure in Windows Form
- How does the Soundex function work in SQL Server?
- Substring after a space
- Copy selected row from datagrid at the end of datagrid
- Error while assigning values to multiple variables in a single select (sql)
- Add some symbols to row
- SQL Server Unicode queries with SC Collation
- When do the missing index DMVs get cleared?
- Find rows matching a value and not matching another
- sql server return long.parse show error
- Attempted to perform an unauthorized operation when executing SQL Server 2019 service pack
- design query in editor (left outer join)
- foreign key data deletion should display error for primary key
- How to execute a 32 bit SSIS package in a 64bit package?
- BigQuery - How to create a new column where the calculation includes the new column itself?
- How to compare results from Invoke-Sqlcmd?
- How do i do this in a trigger SQL Server
- Create new SQLCommand's or reuse the same one
- How to call DB function from EF LINQ query?
- How to prevent Hibernate formula annotation of adding table name before reserved words?
- Stored procedure with conditional Where clause in SQL Server
- What does App=EntityFramework do in Sql connection string?
- I want to allow a single repeated value in a SQL Unique constraint
- SQLSTATE[IMSSP]: Tried to bind parameter number 2101. SQL Server supports a maximum of 2100 parameters
- difference between two consecutive date in days in sql server
- How to count business days from a given date in SQL Server using a calendar reference table
- error in date time format while deployment
- To use a FK in a one-to-many relationship versus using a join table
- Combine multiple rows by summing up some of its columns
- SQL Server 2000 - Update rows and return updated rows
- Easy SQL Server - VS.NET data migration
- Round in MS SQL on 0.05 or 0.00
- SOQL - Convert Date To Owner Locale
- Using GUID Primary Keys & Auto-Increment Primary Keys on different tables in the same DB
- ROW_NUMBER() ORDER BY, can't use column within same SELECT statement
- How to edit the sql query that Entity framework generated?
- Pivot with all data only column change
- SQL Server linked server will not connect
- Migration of huge quantities of data to SQL
- SQL query get record table A based on parentid Table B
- DB Aggregation and BI Best Practices
- SQL Server: Merge Data Rows in single table in output
- How can I populate my database's all tables with random data?
- Microsoft SQL Server Analysis Services OLAP cube
- Self join issue
- SSIS SqlServer 2016 DTS ComponentMetaDataCollection always empty
- Need help in designing a database schema for a SaaS application
- Group Count in T/SQL
- MSSQL 2000 database error while using GROUP BY clause
- how to Transfer data from a table to another table with more columns?
- WCF/Entity Framework with External SQL Server DB Does Not Work when Deployed to IIS
- Count percentage in SQL Server query
- Need for Reorganize/Rebuild indexes after frequent DELETE?
- Appending to lists results from SQL
- How to outer join multiple instances of same table
- Running into misbehaviour during hashing the password field
- How do I get the "Next available number" from an SQL Server? (Not an Identity column)
- Don't want the excess tag in my FOR XML Path('td')
- select rows where certain field appears only in multiple rows
- SQL Server Generate Script To Fill Tables With Data From Other Database?
- Aliasing a linked server?
- How can I SUM a COUNT(*) subquery to find two string values per ID?
- Why does String.Format work but SqlCommand.Parameters.Add not?
- Using non clustered index for efficient searching
- Joining SQL Tables and display columns as rows to generate a report
- Using a running total calculated column in SQL Server table variable
- Arithmetic overflow error converting IDENTITY to data type int
- SQL Server removing entries with duplicated information
- How to store multiple database columns into an array with Linq2Sql
- SQL Delete not gettng the results i need. subquery, outer join
- Pass parameters to stored procedure
- How to Split two column in same table in SQL Sever
- Get Parameter as Column Name in SQL Function
- SQL Geography Latitude/Longitude distance calc
- SQL Server TPH (Table Per Hierarchy) auto increment multiple columns base on type
- Microsoft Sql Server statement using MERGE is executed for table but never for another table
- Can I use a trigger to create a column?
- Procedure to compare two columns from different tables and make the insert
- Can I retrieve the impacted constraint(s) from a InvalidConstraintException?
- regarding some stored proceedure
- SQL: Add values to STDEVP calculation
- SQL Server : randomize rows (shuffle IDs)
- How Useful are Transactions
- Track all logins on to a single SQL Server database
- SQL exception which only occurs on one of the three servers
- Is there a "poor man's" alternative to RedGate for scripting out entire database schema?
- SQL Server, Using Row Number
- sql conversion of a varchar data type to a datetime data type out-of-range
- Concat results from a query
- Find all the columns and keys for multiple tables in one database
- Transaction management and temporary tables in SQL Server
- How to move/copy all databases with users, schema and roles from one server to another
- SQL COUNT DISTINCT NOT RIGHT OUTPUT
- Issue with NULL values using NOT IN
- Concatenate results in select
- T-Sql Sum Positive and Negative Float Value
- Add zero/zeros after fix characters, number of zeros vary MSSQL
- SQL query to get a calculated column based on few conditions on existing columns
- Huge Errorlog with SQL Server 2005 Express (15GB)
- check is there any weekday inside time given sql server
- char cast vs Convert.ToChar()
- Compare data of one table with another based on date & Time
- Split Columns into two equal number of Rows
- How can I reference a single table multiple times in the same query?
- Getting select statement results from a stored procedure using JPA?
- Find values in between two characters '(' and ')'
- How can I make HTTP request from SQL server?
- SQL Query Theory Question
- Displaying float SQL Datatypes
- Shredding xml into table with groups with t-sql
- SQL Server Combining a defined function with other command
- SSRS BIDS expression language Month Part from Current date
- recursive sql query with sub running totals
- Dynamic Pivot Tables based on Dates
- how to analyze slow queries?
- SQL Server Update Fails Based on Another Table?
- Trigger: How does the inserted table work? How to access its rows?
- Count records by Grouping a period
- SQLCMD - SQL Server Job
- Insert "Golf" fails in SQL Server with error unclosed quotation mark
- Converting MS Access IIF to SQL Server CASE statement
- Sanitize search string for Dynamic SQL Queries
- Pass Arraylst<Arraylist<String>> to MSSQL Stored procedure using JAVA?
- When calling stored procedure, .hasRows keeps staying "false"
- Glassfish/Toplink and sqljdbc.jar retrying forever on broken db-connection
- SQL: Counting Problem relating to two tables
- SQL Server : get max/min possible date without magic numbers
- SSRS 2014 issue with dataset after deployment
- Slow inital query when using FreeTextTable in SQL Server 2005
- How can I keep a live copy of a sql server 2000 table when the copied table might have a different schema? Using triggers?
- Division inside Insert stored procedure T-SQL
- Generate initial database migration script from existing schema
- creating an efficient query with a UNION
- Insert into SQL table
- SQL data returned on 2 lines instead of 1
- Compressing VARCHAR in SQL 2008/12 - not seeing results
- Documentation Template for SSAS Cube
- SQL Convert Variable Value into Readable Code
- SQL Agent Job doesn't execute SSIS package, but doesn't fail
- Sql constraint method returns a false value
- Is there a Profiler equivalent for MySql?
- node.js is not connecting to SQL Server database using SQL Server authentication
- ADO recordset has no recordcount with source set to ADO command (stored procedure)
- How can I get the list of all tables used in all the stored procedures of a particular schema?
- TransactionProxyException is thrown while creating a BizTalk Group