CLR table-valued functions

Source: Internet
Author: User

These days, we have worked hard to learn the CLR's stored procedures, create and deploy. From normal stored procedures, with parameters, and output return values.

Insus.net today to learn an example of how to implement the CLR table-valued function. In the database, we can see many kinds of function types, table-falued function,scalar-valued functions and so on.

The functions written in the CLR of this exercise are table-valued function.

In the VS development SQL CLR program, there are simple and complex, look at development time measurement. Some cannot be implemented in SQL, and can be written to the CLR before being deployed to SQL. This article does not see the advantages between the two, is only an example for reference.

For example, we want to create a multi-table query left JOIN. Write the SQL statement as a table-valued function. This multi-table query, the returned field, is defined as a category:



In the code example above, you can copy the code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Data.SqlTypes;usingSystem.Text;namespaceinsus.net{classFruit { Public byteFRUIT_NBR {Get;Set; }  Public byteFRUITCATEGORY_NBR {Get;Set; }  Public stringCategoryName {Get;Set; }  Public byteFRUITKIND_NBR {Get;Set; }  Public stringKindname {Get;Set; }  Public stringFruitname {Get;Set; } }}
View Code


Create a new item:


Follow the steps below to select SQL CLR C # User Defined Function in tag 5.

Mark 6, give a name, Mark 7 "Add" after:


Remove the #14 to #19 Line code and add the following code:


The above code example can be complex code:

usingSystem;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Data.SqlTypes;usingMicrosoft.SqlServer.Server;usingSystem.Collections;usinginsus.net;usingSystem.Collections.Generic; Public Partial classuserdefinedfunctions{[SqlFunction (DataAccess=Dataaccesskind.read, FillRowMethodName="Item_fillrow", TableDefinition="FRUIT_NBR TINYINT,FRUITCATEGORY_NBR TINYINT,"+"CategoryName NVARCHAR (+), Fruitkind_nbr TINYINT,"+"kindname NVARCHAR (+), Fruitname NVARCHAR (in)"                 )    ]     Public StaticIEnumerable tvf_fruit () {List<Fruit> fruitconnections =NewList<fruit>(); using(SqlConnection connection =NewSqlConnection ("Context Connection=true") {connection.            Open (); stringsql ="SELECT [Fruit_nbr],[fruitcategory_nbr],[categoryname],"+"U_FK. [Fruitkind_nbr],[kindname],[fruitname] FROM [dbo]. [Fruit] As F"+"Left JOIN [dbo]. [Udf_fruitkind] () as U_FK on (F.[FRUITKIND_NBR] = u_fk.[ FRUITKIND_NBR])"; using(SqlCommand command =NewSqlCommand (SQL, connection)) {                using(SqlDataReader OBJDR =command. ExecuteReader ()) { while(Objdr.read ()) {Fruit Ofruit=NewInsus.NET.Fruit (); OFRUIT.FRUIT_NBR= (byte) objdr["FRUIT_NBR"]; OFRUIT.FRUITCATEGORY_NBR= (byte) objdr["FRUITCATEGORY_NBR"]; Ofruit.categoryname= objdr["CategoryName"].                        ToString (); OFRUIT.FRUITKIND_NBR= (byte) objdr["FRUITKIND_NBR"]; Ofruit.kindname= objdr["Kindname"].                        ToString (); Ofruit.fruitname= objdr["Fruitname"].                        ToString ();                    Fruitconnections.add (Ofruit); }                }            }        }        returnfruitconnections; }    Private Static voidItem_fillrow (ObjectSource outSqlByte FRUIT_NBR, outSqlByte FRUITCATEGORY_NBR, outSqlChars CategoryName, outSqlByte FRUITKIND_NBR, outSqlChars Kindname, outSqlChars Fruitname) {Fruit Fruit=(Fruit) source; FRUIT_NBR=NewSqlByte (fruit.        FRUIT_NBR); FRUITCATEGORY_NBR=NewSqlByte (fruit.        FRUITCATEGORY_NBR); CategoryName=NewSqlChars (fruit.        CategoryName); FRUITKIND_NBR=NewSqlByte (fruit.        FRUITKIND_NBR); Kindname=NewSqlChars (fruit.        Kindname); Fruitname=NewSqlChars (fruit.    Fruitname); }}
View Code


Next, Build, and then you can deploy to SQL.


You can copy the code above:

IF EXISTS(SELECT *  fromSys.objectsWHEREName= 'Tvf_fruit')    DROP FUNCTIONTvf_fruit;GOIF EXISTS(SELECT *  fromSys.assembliesWHEREName= 'FRUITCLR')    DROPASSEMBLY fruitclr;GOCREATEASSEMBLY fruitclr from 'E:\FruitClr.dll'  withPermission_set=SAFE;GOCREATE FUNCTIONtvf_fruit ()RETURNS TABLE(FRUIT_NBRTINYINT, Fruitcategory_nbrTINYINT, CategoryNameNVARCHAR( -), Fruitkind_nbrTINYINT, KindnameNVARCHAR( -), FruitnameNVARCHAR( -)) asEXTERNAL NAME[FRUITCLR]. Userdefinedfunctions.tvf_fruit;GO
View Code


After successful execution, you will definitely find two locations where SQL has changed:


At this point the table-valued function is created successfully, and the Tvf_fruit () function is executed in Query Analyzer.

CLR table-valued functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.