callisto
callisto

Reputation: 5083

SQL Server: how to do math calculations in a string?

I have an application that allows calculations on input data before writing it to a table.

None of the calculations can be done in C#, all must be done in T-SQL.

The application builds an insert statement with possible nested calculations based on user input.

One sample is an integer that is divided by 10 and then cast to varchar.

 CAST(( ' ( CAST( 6828 AS BIGINT)) /10' ) AS NVARCHAR(MAX)) ,

This is part of a larger INSERT statement that is built based on user interface input.

How would I get the inner part ( CAST( 6828 AS BIGINT)) /10 executed first?

Upvotes: 0

Views: 2007

Answers (1)

Brian Knight
Brian Knight

Reputation: 5041

You can use sp_executesql to execute an entire string. For instance:

EXEC sp_executesql N'SELECT CAST( CAST( 6828 AS BIGINT)) /10 AS NVARCHAR(MAX))';

See more here.

Upvotes: 1

Related Questions