Convert octal to decimal in SQL - sql-server

A friend asked how in SQL to convert a varchar which represents an octal value into integer, so I'm placing an answer here and seeing if anyone improves upon it.
I had hoped for a solution that could be run inline as part of query, without having to create any function in the database (e.g if you only have permission to query a database, but not create any new functions or stored procedures in it).
Alternatively, I see that .Net Framework ToInt32 method has easy way of doing this, but seems like jumping through a lot of CLR integration hoops required to get there.

Somewhat convoluted - requiring a 2-level scalar subquery
Setup & Query
declare #t table (oct varchar(10));
insert #t select '7101';
insert #t select '6';
insert #t select '110111';
select *,
(select sum(val)
from
(
select substring(reverse(t.oct), v.number, 1) * power(8, v.number-1) val
from master..spt_values v
where v.type='p' and v.number between 1 and len(t.oct)
) x
) intVal
from #t t;
Results
oct intVal
---------- -----------
7101 3649
6 6
110111 36937

Here is my quick-n-dirty iterative version:
CREATE FUNCTION dbo.fn_OctalToInt(#OctalVal varchar(50)) RETURNS BIGINT AS
BEGIN
DECLARE #pos tinyint = 0
DECLARE #tot bigint = 0
WHILE #pos < LEN(#OctalVal) BEGIN
set #tot = #tot + cast(SUBSTRING(#OctalVal, len(#OctalVal) - #pos, 1) as tinyint) * power(8,#pos)
set #pos = #pos + 1
END
RETURN #tot
END

Related

How to find how many times repeat number in comma separated value in particular column in SQL Server

I have a SQL Server table as shown below, in that one column contains comma-separated integer values. What I want is to get particular number with count as below expected result
Edited:
I know how to split the comma separated value. but my problem is output that I want. see the expected output in that count column shows in all table howmnay times particular number repeat.
For example :
Id values
---------------
1 2,3
2 1,2,3
3 1,3
4 2,3
Expected result :
number repeat count
--------------
1 2
2 3
3 4
Can anyone help me with this? How to write the query to get this desired output?
Thanks in advance
It looks like the question is how to aggregate the results of a SPLIT function, not how to split the values.
SQL Server 2016 provides the built-in STRING_SPLIT function to split a delimited string and return the values as a table. Individual values are returned in the value field. The following query groups the value field and returns the count:
declare #table table (id int, somevalues nvarchar(200))
insert into #table
values
(1,N'2,3'),
(2,N'1,2,3'),
(3,N'1,3'),
(4,N'2,3')
select value,count(* )
from #table
cross apply string_split(somevalues,',')
group by value
The same query can be used in previous versions as long as a split function is available. Almost all of the available techniques are described in Aaron Bertrand's articles like this one and this follow up. The fastest methods use CLR and XML.
The queries are the same, the only things that change are the names of the columns returned by the split function, eg:
select item,count(* )
from #table
cross apply dbo.SplitStrings_XML(somevalues,',')
group by item
In both cases the result is :
value (No column name)
1 2
2 3
3 4
First create split function like this
CREATE FUNCTION SplitString (
#Input NVARCHAR(MAX)
, #Character CHAR(1)
)
RETURNS #Output TABLE (Item NVARCHAR(1000))
AS
BEGIN
DECLARE #StartIndex INT
, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output (Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
GO
then you can adapt the query as follows
create table #temp(
id int,
test varchar(20)
)
insert into #temp (id,test) values (1,'1,2,3')
SELECT t.id, count(sf.Item)
FROM #temp AS t
CROSS APPLY dbo.SplitString(t.test,',') AS sf
group by t.id;
drop table #temp

How I can replace all values in table dynamically in SQL Server 2012?

My current table is like
where UserId has 14 columns from ys_ar_item1 to ys_ar_item14 for multiple clients. I have to change or update the values in this table such that 0 should be replaced by 1, 1 should be replaced by 2, 2 should be replaced by 3 up to 6 should be replaced by 7, and nil should be replaced by 0.
For example: ys_ar_item1 should be 31245 instead of 20134.
Here is Sample table for 3 columns, it will be for all columns that is 14.
Note - It would be fine to create a new table with UserId and 14 columns.
Like already mentioned, this is a bad database design.
But you can try the following function to get the desired result:
CREATE FUNCTION ReplaceNumbers
(
#str varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
DECLARE #result varchar(max)
DECLARE #cnt int=1
WHILE #cnt <= LEN(#str)
BEGIN
SET #result = CONCAT(#result,
CASE WHEN SUBSTRING(#str,#cnt,1) IN ('0','1','2','3','4','5','6')
THEN CAST(PARSE(SUBSTRING(#str,#cnt,1) AS int)+1 AS varchar)
ELSE SUBSTRING(#str,#cnt,1) END)
SET #cnt = #cnt + 1
END;
RETURN REPLACE(#result, 'nil', '0')
END
Use it like this:
UPDATE myTable SET ys_ar_item1=dbo.ReplaceNumbers(ys_ar_item1)
It's really bad design and you store numbers as strings which makes things hard, but I can think just of using those functions IIF(), TRY_CAST() and REPLICATE():
CREATE TABLE Sample (
UserID INT,
Ys_Ar_Item1 VARCHAR(10),
Ys_Ar_Item2 VARCHAR(10),
Ys_Ar_Item3 VARCHAR(10)
-- Other columns
);
INSERT INTO Sample VALUES
(1, '20134', 'nil NULL', '02341');
SELECT UserID,
IIF(TRY_CAST(Ys_Ar_Item1 AS INT) IS NULL, '0', CAST( REPLICATE('1', LEN(Ys_Ar_Item1) ) AS INT) + CAST(Ys_Ar_Item1 AS INT)) AS Ys_Ar_Item1,
IIF(TRY_CAST(Ys_Ar_Item2 AS INT) IS NULL, '0', CAST( REPLICATE('1', LEN(Ys_Ar_Item2) ) AS INT) + CAST(Ys_Ar_Item2 AS INT)) AS Ys_Ar_Item2,
IIF(TRY_CAST(Ys_Ar_Item3 AS INT) IS NULL, '0', CAST( REPLICATE('1', LEN(Ys_Ar_Item3) ) AS INT) + CAST(Ys_Ar_Item3 AS INT)) AS Ys_Ar_Item3
FROM Sample;
Note:
In the sample data you include in your question as an image, there is no number >6, this solution will fail if you have such numbers.

Converting text to binary code - TSQL

I found a few threads on this using the search feature, but nothing for a purely T-SQL solution.
the need - A system is storing a weekly schedule as 0's and 1's in a string format to represent a week. 1 means yes, 0 means no....so 1100111 means sunday yes (first one), Monday yes (second 1), Tuesday no (the 0)...etc.
Short question - How do I go from an ascii char such as '>' to it's hex code '3E' and ultimately to it's binary '00111110' representation?
Long question - I'm extracting from a flat file system that stores a table as:
ID int,
priority_1 varchar(2)
...
It actually goes to priroity_128 (silly flat file), but I'm only interested in 1-7 and the logic for one should be easily reused for the others. I unfortunately have no control over this part of the extract. The values I get look like:
1 >
2 (edit, I actually put a symbol here that I receive from the system but the forum doesn't like.)
3 |
4 Y
I get the feeling these are appearing as their ascii chars because of the conversion as I extract.
select convert(varbinary,'>',2)
This returns 0x3E. The 0x part can be ignored... 3 in binary is 0011 and E is 1110...3E = 00111110. Trim the first 0 and it leaves the 7 bit code that I'm looking for. Unfortunately I have no idea how to express this logic here in T-SQL. Any ideas? I'm thinking as a function would be easiest to use...something like:
select id, binaryversionof(priority_1)
Here's a UDF that will convert from base-10 to any other base, including base-2...
Here's how you can use it:
SELECT YourDatabase.dbo.udf_ConvertFromBase10(convert(varbinary, '>', 2), 2)
Here's what it returns:
111110
And here's the function definition:
CREATE FUNCTION [dbo].[udf_ConvertFromBase10]
(
#num INT,
#base TINYINT
)
RETURNS VARCHAR(255)
AS
BEGIN
-- Check for a null value.
IF (#num IS NULL)
RETURN NULL
-- Declarations
DECLARE #string VARCHAR(255)
DECLARE #return VARCHAR(255)
DECLARE #finished BIT
DECLARE #div INT
DECLARE #rem INT
DECLARE #char CHAR(1)
-- Initialize
SELECT #string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
SELECT #return = CASE WHEN #num <= 0 THEN '0' ELSE '' END
SELECT #finished = CASE WHEN #num <= 0 THEN 1 ELSE 0 END
SELECT #base = CASE WHEN #base < 2 OR #base IS NULL THEN 2 WHEN #base > 36 THEN 36 ELSE #base END
-- Loop
WHILE #finished = 0
BEGIN
-- Do the math
SELECT #div = #num / #base
SELECT #rem = #num - (#div * #base)
SELECT #char = SUBSTRING(#string, #rem + 1, 1)
SELECT #return = #char + #return
SELECT #num = #div
-- Nothing left?
IF #num = 0 SELECT #finished = 1
END
-- Done
RETURN #return
END
Your solution returns a string of a variable length. Not sure whether it was by design or you simply overlooked that fact.
Anyway, here's my solution, which always returns 7 0s or 1s:
CREATE FUNCTION fnIntTo7Bits (#Value int)
RETURNS varchar(7)
AS BEGIN
DECLARE #Bits varchar(7);
SELECT #Bits = COALESCE(#Bits, '') + CAST(CAST(#Value & number AS bit) AS varchar)
FROM master..spt_values
WHERE type = 'P' AND number IN (1, 2, 4, 8, 16, 32, 64)
ORDER BY number DESC;
RETURN #Bits;
END;
The master..spt_values table is a system table used internally but also accessible to the user. It seems to have been inherited from Sybase so it's a very old tool, which, to my mind, means it won't go too soon.
But if you like, you can use your own number table, which you don't even have to materialise, like this:
...
SELECT #Bits = COALESCE(#Bits, '') + CAST(CAST(#Value & number AS bit) AS varchar)
FROM (
SELECT 1 UNION ALL SELECT 2 UNION ALL
SELECT 4 UNION ALL SELECT 8 UNION ALL
SELECT 16 UNION ALL SELECT 32 UNION ALL SELECT 64
) s (number)
ORDER BY number DESC;
...
Answering my own question...though curious if anyone has something more elegant. I found this unsourced function using google:
CREATE FUNCTION udf_bin_me (#IncomingNumber int)
RETURNS varchar(200)
as
BEGIN
DECLARE #BinNumber VARCHAR(200)
SET #BinNumber = ''
WHILE #IncomingNumber <> 0
BEGIN
SET #BinNumber = SUBSTRING('0123456789', (#IncomingNumber % 2) + 1, 1) + #BinNumber
SET #IncomingNumber = #IncomingNumber / 2
END
RETURN #BinNumber
END
Then use the Ascii function to get the char to it's ascii decimal value:
select dbo.udf_bin_me(ascii('>'))
Seems to be a bit of a run around, but I can work from that. Better solution anyone?
I just whipped this up, it maybe buggy... but it works:
DECLARE #value INT, #binary VARCHAR(10)
SELECT #value = ASCII('m'), #binary = ''
;WITH [BINARY] ([Location], [x], [BIT])
AS
(
-- Base case
SELECT 64, #value, #value % 2
UNION ALL
-- Recursive
SELECT [BINARY].[Location] / 2, [BINARY].[x] / 2, ([BINARY].[x] / 2) % 2
FROM [BINARY]
WHERE [BINARY].[Location] >= 2
)
SELECT #binary = CAST([BIT] AS CHAR(1)) + #binary FROM [BINARY]
SELECT #binary

Looking for a General "Minimum" User Defined Function

I created the following function to simplify a piece of particularly complex code.
CREATE FUNCTION [dbo].[DSGetMinimumInt] (#First INT, #Second INT)
RETURNS INT
AS
BEGIN
IF #First < #Second
RETURN #First
RETURN #Second
END
However, it only works for the INT datatype. I know I could create one for numeric and possibly for Varchar and Datetime.
Is it possible to create one master "Minimum" function to deal with them all? Has anyone done this?
I've Googled it, but come up empty.
here is a basic one you can work with, I'd be careful using this in queries, as it will slow them down in proportion to the number of rows it is used on:
CREATE FUNCTION [dbo].[DSGetMinimum] (#First sql_variant, #Second sql_variant)
RETURNS varchar(8000)
AS
BEGIN
DECLARE #Value varchar(8000)
IF SQL_VARIANT_PROPERTY(#First,'BaseType')=SQL_VARIANT_PROPERTY(#Second,'BaseType')
OR #First IS NULL OR #Second IS NULL
BEGIN
IF SQL_VARIANT_PROPERTY(#First,'BaseType')='datetime'
BEGIN
IF CONVERT(datetime,#First)<CONVERT(datetime,#Second)
BEGIN
SET #Value=CONVERT(char(23),#First,121)
END
ELSE
BEGIN
SET #Value=CONVERT(char(23),#Second,121)
END
END --IF datetime
ELSE
BEGIN
IF #First < #Second
SET #Value=CONVERT(varchar(8000),#First)
ELSE
SET #Value=CONVERT(varchar(8000),#Second)
END
END --IF types the same
RETURN #Value
END
GO
EDIT
Test Code:
DECLARE #D1 datetime , #D2 datetime
DECLARE #I1 int , #I2 int
DECLARE #V1 varchar(5) , #V2 varchar(5)
SELECT #D1='1/1/2010', #D2='1/2/2010'
,#I1=5 , #I2=999
,#V1='abc' , #V2='xyz'
PRINT dbo.DSGetMinimumInt(#D1,#D2)
PRINT dbo.DSGetMinimumInt(#I1,#I2)
PRINT dbo.DSGetMinimumInt(#V1,#V2)
Test Output:
2010-01-01 00:00:00.000
5
abc
If you are going to use this in a query, I would just use an inline CASE statement, which would be MUCH faster then the UDF:
CASE
WHEN #valueAnyType1<#ValueAnyType2 THEN #valueAnyType1
ELSE #ValueAnyType2
END
you can add protections for NULL if necessary:
CASE
WHEN #valueAnyType1<=ISNULL(#ValueAnyType2,#valueAnyType1) THEN #valueAnyType1
ELSE #ValueAnyType2
END
All major databases except SQL Server support LEAST and GREATEST which do what you want.
In SQL Server, you can emulate it this way:
WITH q (col1, col2) AS
(
SELECT 'test1', 'test2'
UNION ALL
SELECT 'test3', 'test4'
)
SELECT (
SELECT MIN(col)
FROM (
SELECT col1 AS col
UNION ALL
SELECT col2
) qa
)
FROM q
, though it will be a little bit less efficient than a UDF.
Azure SQL DB (and future SQL Server versions) now supports GREATEST/LEAST:
GREATEST
LEAST

Is there a way to make a TSQL variable constant?

Is there a way to make a TSQL variable constant?
No, but you can create a function and hardcode it in there and use that.
Here is an example:
CREATE FUNCTION fnConstant()
RETURNS INT
AS
BEGIN
RETURN 2
END
GO
SELECT dbo.fnConstant()
One solution, offered by Jared Ko is to use pseudo-constants.
As explained in SQL Server: Variables, Parameters or Literals? Or… Constants?:
Pseudo-Constants are not variables or parameters. Instead, they're simply views with one row, and enough columns to support your constants. With these simple rules, the SQL Engine completely ignores the value of the view but still builds an execution plan based on its value. The execution plan doesn't even show a join to the view!
Create like this:
CREATE SCHEMA ShipMethod
GO
-- Each view can only have one row.
-- Create one column for each desired constant.
-- Each column is restricted to a single value.
CREATE VIEW ShipMethod.ShipMethodID AS
SELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]
,CAST(2 AS INT) AS [ZY - EXPRESS]
,CAST(3 AS INT) AS [OVERSEAS - DELUXE]
,CAST(4 AS INT) AS [OVERNIGHT J-FAST]
,CAST(5 AS INT) AS [CARGO TRANSPORT 5]
Then use like this:
SELECT h.*
FROM Sales.SalesOrderHeader h
JOIN ShipMethod.ShipMethodID const
ON h.ShipMethodID = const.[OVERNIGHT J-FAST]
Or like this:
SELECT h.*
FROM Sales.SalesOrderHeader h
WHERE h.ShipMethodID = (SELECT TOP 1 [OVERNIGHT J-FAST] FROM ShipMethod.ShipMethodID)
My workaround to missing constans is to give hints about the value to the optimizer.
DECLARE #Constant INT = 123;
SELECT *
FROM [some_relation]
WHERE [some_attribute] = #Constant
OPTION( OPTIMIZE FOR (#Constant = 123))
This tells the query compiler to treat the variable as if it was a constant when creating the execution plan. The down side is that you have to define the value twice.
No, but good old naming conventions should be used.
declare #MY_VALUE as int
There is no built-in support for constants in T-SQL. You could use SQLMenace's approach to simulate it (though you can never be sure whether someone else has overwritten the function to return something else…), or possibly write a table containing constants, as suggested over here. Perhaps write a trigger that rolls back any changes to the ConstantValue column?
Prior to using a SQL function run the following script to see the differences in performance:
IF OBJECT_ID('fnFalse') IS NOT NULL
DROP FUNCTION fnFalse
GO
IF OBJECT_ID('fnTrue') IS NOT NULL
DROP FUNCTION fnTrue
GO
CREATE FUNCTION fnTrue() RETURNS INT WITH SCHEMABINDING
AS
BEGIN
RETURN 1
END
GO
CREATE FUNCTION fnFalse() RETURNS INT WITH SCHEMABINDING
AS
BEGIN
RETURN ~ dbo.fnTrue()
END
GO
DECLARE #TimeStart DATETIME = GETDATE()
DECLARE #Count INT = 100000
WHILE #Count > 0 BEGIN
SET #Count -= 1
DECLARE #Value BIT
SELECT #Value = dbo.fnTrue()
IF #Value = 1
SELECT #Value = dbo.fnFalse()
END
DECLARE #TimeEnd DATETIME = GETDATE()
PRINT CAST(DATEDIFF(ms, #TimeStart, #TimeEnd) AS VARCHAR) + ' elapsed, using function'
GO
DECLARE #TimeStart DATETIME = GETDATE()
DECLARE #Count INT = 100000
DECLARE #FALSE AS BIT = 0
DECLARE #TRUE AS BIT = ~ #FALSE
WHILE #Count > 0 BEGIN
SET #Count -= 1
DECLARE #Value BIT
SELECT #Value = #TRUE
IF #Value = 1
SELECT #Value = #FALSE
END
DECLARE #TimeEnd DATETIME = GETDATE()
PRINT CAST(DATEDIFF(ms, #TimeStart, #TimeEnd) AS VARCHAR) + ' elapsed, using local variable'
GO
DECLARE #TimeStart DATETIME = GETDATE()
DECLARE #Count INT = 100000
WHILE #Count > 0 BEGIN
SET #Count -= 1
DECLARE #Value BIT
SELECT #Value = 1
IF #Value = 1
SELECT #Value = 0
END
DECLARE #TimeEnd DATETIME = GETDATE()
PRINT CAST(DATEDIFF(ms, #TimeStart, #TimeEnd) AS VARCHAR) + ' elapsed, using hard coded values'
GO
If you are interested in getting optimal execution plan for a value in the variable you can use a dynamic sql code. It makes the variable constant.
DECLARE #var varchar(100) = 'some text'
DECLARE #sql varchar(MAX)
SET #sql = 'SELECT * FROM table WHERE col = '''+#var+''''
EXEC (#sql)
For enums or simple constants, a view with a single row has great performance and compile time checking / dependency tracking ( cause its a column name )
See Jared Ko's blog post https://blogs.msdn.microsoft.com/sql_server_appendix_z/2013/09/16/sql-server-variables-parameters-or-literals-or-constants/
create the view
CREATE VIEW ShipMethods AS
SELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]
,CAST(2 AS INT) AS [ZY - EXPRESS]
,CAST(3 AS INT) AS [OVERSEAS - DELUXE]
, CAST(4 AS INT) AS [OVERNIGHT J-FAST]
,CAST(5 AS INT) AS [CARGO TRANSPORT 5]
use the view
SELECT h.*
FROM Sales.SalesOrderHeader
WHERE ShipMethodID = ( select [OVERNIGHT J-FAST] from ShipMethods )
Okay, lets see
Constants are immutable values which are known at compile time and do not change for the life of the program
that means you can never have a constant in SQL Server
declare #myvalue as int
set #myvalue = 5
set #myvalue = 10--oops we just changed it
the value just changed
Since there is no build in support for constants, my solution is very simple.
Since this is not supported:
Declare Constant #supplement int = 240
SELECT price + #supplement
FROM what_does_it_cost
I would simply convert it to
SELECT price + 240/*CONSTANT:supplement*/
FROM what_does_it_cost
Obviously, this relies on the whole thing (the value without trailing space and the comment) to be unique. Changing it is possible with a global search and replace.
There are no such thing as "creating a constant" in database literature. Constants exist as they are and often called values. One can declare a variable and assign a value (constant) to it. From a scholastic view:
DECLARE #two INT
SET #two = 2
Here #two is a variable and 2 is a value/constant.
SQLServer 2022 (currently only as Preview available) is now able to Inline the function proposed by SQLMenace, this should prevent the performance hit described by some comments.
CREATE FUNCTION fnConstant() RETURNS INT AS BEGIN RETURN 2 END GO
SELECT is_inlineable FROM sys.sql_modules WHERE [object_id]=OBJECT_ID('dbo.fnConstant');
is_inlineable
1
SELECT dbo.fnConstant()
ExecutionPlan
To test if it also uses the value coming from the Function, I added a second function returning value "1"
CREATE FUNCTION fnConstant1()
RETURNS INT
AS
BEGIN
RETURN 1
END
GO
Create Temp Table with about 500k rows with Value 1 and 4 rows with Value 2:
DROP TABLE IF EXISTS #temp ;
create table #temp (value_int INT)
DECLARE #counter INT;
SET #counter = 0
WHILE #counter <= 500000
BEGIN
INSERT INTO #temp VALUES (1);
SET #counter = #counter +1
END
SET #counter = 0
WHILE #counter <= 3
BEGIN
INSERT INTO #temp VALUES (2);
SET #counter = #counter +1
END
create index i_temp on #temp (value_int);
Using the describe plan we can see that the Optimizer expects 500k values for
select * from #temp where value_int = dbo.fnConstant1(); --Returns 500001 rows
Constant 1
and 4 rows for
select * from #temp where value_int = dbo.fnConstant(); --Returns 4rows
Constant 2
Robert's performance test is interesting. And even in late 2022, the scalar functions are much slower (by an order of magnitude) than variables or literals. A view (as suggested mbobka) is somewhere in-between when used for this same test.
That said, using a loop like that in SQL Server is not something I'd ever do, because I'd normally be operating on a whole set.
In SQL 2019, if you use schema-bound functions in a set operation, the difference is much less noticeable.
I created and populated a test table:
create table #testTable (id int identity(1, 1) primary key, value tinyint);
And changed the test so that instead of looping and changing a variable, it queries the test table and returns true or false depending on the value in the test table, e.g.:
insert #testTable(value)
select case when value > 127
then #FALSE
else #TRUE
end
from #testTable with(nolock)
I tested 5 scenarios:
hard-coded values
local variables
scalar functions
a view
a table-valued function
running the test 10 times, yielded the following results:
scenario
min
max
avg
scalar functions
233
259
240
hard-coded values
236
265
243
local variables
235
278
245
table-valued function
243
272
253
view
244
267
254
Suggesting to me, that for set-based work in (at least) 2019 and better, there's not much in it.
set nocount on;
go
-- create test data table
drop table if exists #testTable;
create table #testTable (id int identity(1, 1) primary key, value tinyint);
-- populate test data
insert #testTable (value)
select top (1000000) convert(binary (1), newid())
from sys.all_objects a
, sys.all_objects b
go
-- scalar function for True
drop function if exists fnTrue;
go
create function dbo.fnTrue() returns bit with schemabinding as
begin
return 1
end
go
-- scalar function for False
drop function if exists fnFalse;
go
create function dbo.fnFalse () returns bit with schemabinding as
begin
return 0
end
go
-- table-valued function for booleans
drop function if exists dbo.tvfBoolean;
go
create function tvfBoolean() returns table with schemabinding as
return
select convert(bit, 1) as true, convert(bit, 0) as false
go
-- view for booleans
drop view if exists dbo.viewBoolean;
go
create view dbo.viewBoolean with schemabinding as
select convert(bit, 1) as true, convert(bit, 0) as false
go
-- create table for results
drop table if exists #testResults
create table #testResults (id int identity(1,1), test int, elapsed bigint, message varchar(1000));
-- define tests
declare #tests table(testNumber int, description nvarchar(100), sql nvarchar(max))
insert #tests values
(1, N'hard-coded values', N'
declare #testTable table (id int, value bit);
insert #testTable(id, value)
select id, case when t.value > 127
then 0
else 1
end
from #testTable t')
, (2, N'local variables', N'
declare #FALSE as bit = 0
declare #TRUE as bit = 1
declare #testTable table (id int, value bit);
insert #testTable(id, value)
select id, case when t.value > 127
then #FALSE
else #TRUE
end
from #testTable t'),
(3, N'scalar functions', N'
declare #testTable table (id int, value bit);
insert #testTable(id, value)
select id, case when t.value > 127
then dbo.fnFalse()
else dbo.fnTrue()
end
from #testTable t'),
(4, N'view', N'
declare #testTable table (id int, value bit);
insert #testTable(id, value)
select id, case when value > 127
then b.false
else b.true
end
from #testTable t with(nolock), viewBoolean b'),
(5, N'table-valued function', N'
declare #testTable table (id int, value bit);
insert #testTable(id, value)
select id, case when value > 127
then b.false
else b.true
end
from #testTable with(nolock), dbo.tvfBoolean() b')
;
declare #testNumber int, #description varchar(100), #sql nvarchar(max)
declare #testRuns int = 10;
-- execute tests
while #testRuns > 0 begin
set #testRuns -= 1
declare testCursor cursor for select testNumber, description, sql from #tests;
open testCursor
fetch next from testCursor into #testNumber, #description, #sql
while ##FETCH_STATUS = 0 begin
declare #TimeStart datetime2(7) = sysdatetime();
execute sp_executesql #sql;
declare #TimeEnd datetime2(7) = sysdatetime()
insert #testResults(test, elapsed, message)
select #testNumber, datediff_big(ms, #TimeStart, #TimeEnd), #description
fetch next from testCursor into #testNumber, #description, #sql
end
close testCursor
deallocate testCursor
end
-- display results
select test, message, count(*) runs, min(elapsed) as min, max(elapsed) as max, avg(elapsed) as avg
from #testResults
group by test, message
order by avg(elapsed);
The best answer is from SQLMenace according to the requirement if that is to create a temporary constant for use within scripts, i.e. across multiple GO statements/batches.
Just create the procedure in the tempdb then you have no impact on the target database.
One practical example of this is a database create script which writes a control value at the end of the script containing the logical schema version. At the top of the file are some comments with change history etc... But in practice most developers will forget to scroll down and update the schema version at the bottom of the file.
Using the above code allows a visible schema version constant to be defined at the top before the database script (copied from the generate scripts feature of SSMS) creates the database but used at the end. This is right in the face of the developer next to the change history and other comments, so they are very likely to update it.
For example:
use tempdb
go
create function dbo.MySchemaVersion()
returns int
as
begin
return 123
end
go
use master
go
-- Big long database create script with multiple batches...
print 'Creating database schema version ' + CAST(tempdb.dbo.MySchemaVersion() as NVARCHAR) + '...'
go
-- ...
go
-- ...
go
use MyDatabase
go
-- Update schema version with constant at end (not normally possible as GO puts
-- local #variables out of scope)
insert MyConfigTable values ('SchemaVersion', tempdb.dbo.MySchemaVersion())
go
-- Clean-up
use tempdb
drop function MySchemaVersion
go

Resources