Reference > Functions > Conversion

Cast

  • 2005, 2008, 2012, 2014, 2016, 2017, 2019, 2022

Cast Conversion Function

Use the Cast function to change the database type of an expression to a different database type.

Syntax

db.fx.Cast({expression}).{data_type_method}([{length}])

Arguments

expression
The field expression, composite element, or function result to use in calculating the population variance.
data_type_method
The method specifying the database type the `expression` should be cast to.
length
For cast operations to database types supporting a 'length' (`varchar`, `char`, `nvarchar`, `nchar`), the length of the database type returned from the cast operation.

Returns

data_type_methodreturn type (based on nullability of expression)
AsBit()bool or bool?
AsSmallInt()byte or byte?
AsInt()int or int?
AsBigInt()long or long?
AsDecimal()decimal or decimal?
AsFloat()float or float?
AsDateTime()DateTime or DateTime?
AsDateTimeOffset()DateTimeOffset or DateTimeOffset?
AsUniqueIdentifier()Guid or Guid?
AsVarChar({length})string or string?
AsChar({length})string or string?
AsNVarChar({length})string or string?
AsNChar({length})string or string?
AsTinyInt()short or short?
AsTime()TimeSpan or TimeSpan?
AsMoney()double or double?
AsMoney()double or double?

Examples

Select Statement

Select the cast of total purchase amount to a varchar(20).

string? result = db.SelectOne(
        db.fx.Cast(dbo.Purchase.TotalPurchaseAmount).AsVarChar(20)
    )
    .From(dbo.Purchase)
    .Execute();

Order By Clause

Select the cast of zip code to an integer.

int cast = db.SelectOne(
        db.fx.Cast(dbo.Address.Zip).AsInt()
    )
    .From(dbo.Address)
    .OrderBy(db.fx.Cast(dbo.Address.Zip).AsInt().Desc())
    .Execute();

Group By Clause

Select the cast of all product quantities, grouped by product category type and cast of product quantity.

IEnumerable<dynamic> values = db.SelectMany(
        dbo.Product.ProductCategoryType,
        db.fx.Cast(dbo.Product.Quantity).AsBigInt().As("Quantity")
    )
    .From(dbo.Product)
    .GroupBy(
        dbo.Product.ProductCategoryType,
        db.fx.Cast(dbo.Product.Quantity).AsBigInt()
    )
    .Execute();

Having Clause

Select the cast of all product quantities, grouped by product category type and cast of product quantity having n casted value less than or equal to 1,000,000.

IEnumerable<dynamic> values = db.SelectMany(
        dbo.Product.ProductCategoryType,
        db.fx.Cast(dbo.Product.Quantity).AsBigInt().As("Quantity")
    )
    .From(dbo.Product)
    .GroupBy(
        dbo.Product.ProductCategoryType,
        dbo.Product.Quantity
    )
    .Having(db.fx.Cast(dbo.Product.Quantity).AsBigInt() <= 1_000_000)
    .Execute();
Previous
Conversion

© 2024 dbExpression. All rights reserved.