Ways to invoke methods on CLR datatypes
-
02-10-2020 - |
Question
I have difficulty understanding when to use .method()
and when to use ::method()
in SQL Server.
For example
- For
HierarchyID
data type I have seenHierarchyID::GetRoot()
, but also@sample_node.GetAncestor(1);
- For Geometry data type,
There is
GEOMETRY::parse()
that is used to insert rows. But there is also methods such as@sample_geometry.ToString()
to output data with better readability.
What are the differences between them?
Solution
The difference is between CLR static methods (type_name::method()
) and instance methods (instance.method()
)
Static methods are defined on the type itself and are generally utility methods that get everything they need to operate passed in as method parameters.
Instance methods operate on an object of a particular datatype and are able to access the private state of that object and mutate the object or return a result that uses that state.
HierarchyID::GetRoot()
always returns the same result.
@sample_node.GetAncestor(1);
will return a different result dependent On what @sample_node
is.
OTHER TIPS
Are you referring to calling SQL objects from .NET code (such as C#, VB, C++)? Or are you referring to calling .NET methods from SQL Objects?
The syntax you are using is not valid MS SQL syntax. Common MS SQL Syntax is:
Database.schema.Column
Database.schema.Function(arg) OR schema.function
Database.schema.StoredProcedure(arg/param) OR schema.StoredProcedure (arg/param)
Database.Schema.Table
Table.Column
If you are looking to call a method by passing a column as an argument, the syntax would be:
schema.function(table.column)
Example:
SELECT
getHashedPassword(Users.Password)
FROM Users