As the name suggests: table-valued returns table, however Scalar-valued returns a single value, such as a string, integer, or bit value.
1、table-valued function
As to create table-valued function, there are 2 ways, look at the example below please, it’s suitable for simple logic:
USE Redgate CREATE TABLE DBO.TestCount_1(ID int,C1 VARCHAR(400),C2 VARCHAR(300),C3 VARCHAR(150) NOT NULL,C4 VARCHAR(80),C5 VARCHAR(38) NOT NULL) CREATE TABLE DBO.TestCount_2(ID int,C1 VARCHAR(400),C2 VARCHAR(300),C3 VARCHAR(150) NOT NULL,C4 VARCHAR(80),C5 VARCHAR(38) NOT NULL) DECLARE @COUNT INT =1 SET NOCOUNT ON WHILE @COUNT<=150 BEGIN INSERT DBO.TestCount_1(ID, C1, C2, C3, C4, C5) SELECT @COUNT,NEWID(),NEWID(),NEWID(),NEWID(),NEWID() INSERT DBO.TestCount_2(ID, C1, C2, C3, C4, C5) SELECT @COUNT,NEWID(),NEWID(),NEWID(),NEWID(),NEWID() SET @COUNT=@COUNT+1 END
Create funcation
USE Redgate; GO CREATE FUNCTION DBO.TestCount (@ID int) RETURNS TABLE AS RETURN ( SELECT A.* FROM DBO.TestCount_1 A,DBO.TestCount_2 B WHERE A.ID =B.ID AND A.ID=@ID ); GO
You can use below statement to query:
SELECT * FROM TestCount(5)
For more complex logic, more statements, you can use another table-valued function, look at the example below:
USE Redgate; GO CREATE FUNCTION dbo.TestCount_Complex (@ID int) RETURNS @Return_TestCount TABLE ( ID int, C1 VARCHAR(38), C2 VARCHAR(38), C3 VARCHAR(38) ) AS BEGIN INSERT INTO @Return_TestCount(ID,C1,C2,C3) SELECT ID,C1,C2,C3 FROM DBO.TestCount_1 WHERE ID=@ID INSERT INTO @Return_TestCount(ID,C1,C2,C3) SELECT ID,C1,C2,C3 FROM DBO.TestCount_2 WHERE ID=@ID RETURN END; GO
Use this statement to call the function:
SELECT * FROM TestCount_Complex(5)
2、Scalar-valued functions
It’s easy than table-valued function, look the sample:
CREATE FUNCTION [dbo].TestCount_SVF ( @ID int ) RETURNS VARCHAR(50) AS BEGIN declare @nodeCount VARCHAR(50) select @nodeCount=C2 from TestCount_1 WHERE ID=@ID return @nodeCount END --SELECT DBO.TestCount_SVF(5)
Mark:
1、table-valued function can join table, but Scalar-valued functions can not join table.
SELECT * FROM TestCount(5) A,TestCount_1 B WHERE A.ID=B.ID
2、table-valued function can not nest in table, but Scalar-valued functions can do it.
SELECT DBO.TestCount_SVF(5), * FROM TestCount_1
3、call table-valued function is :
SELECT * FROM TestCount(5)
but Scalar-valued functions is:
SELECT DBO.TestCount_SVF(5)
4、if their schema is dbo, call table-valued function can:
SELECT * FROM TestCount(5)
but Scalar-valued functions must add “dbo”:
SELECT DBO.TestCount_SVF(5)