TSQL 변수를 상수로 만드는 방법이 있습니까?
TSQL 변수를 상수로 만드는 방법이 있습니까?
아니요,하지만 함수를 만들고 거기에 하드 코딩하여 사용할 수 있습니다.
다음은 예입니다.
CREATE FUNCTION fnConstant()
RETURNS INT
AS
BEGIN
RETURN 2
END
GO
SELECT dbo.fnConstant()
상수 누락에 대한 내 해결 방법은 최적화 프로그램에 값에 대한 힌트를 제공하는 것입니다.
DECLARE @Constant INT = 123;
SELECT *
FROM [some_relation]
WHERE [some_attribute] = @Constant
OPTION( OPTIMIZE FOR (@Constant = 123))
이것은 실행 계획을 생성 할 때 변수를 상수 인 것처럼 처리하도록 쿼리 컴파일러에 지시합니다. 단점은 값을 두 번 정의해야한다는 것입니다.
의사 상수는 변수 나 매개 변수가 아닙니다. 대신 단순히 하나의 행과 상수를 지원하기에 충분한 열이있는보기입니다. 이러한 간단한 규칙을 통해 SQL 엔진은 뷰의 값을 완전히 무시하지만 여전히 해당 값을 기반으로 실행 계획을 작성합니다. 실행 계획은 뷰에 대한 조인도 표시하지 않습니다!
아니요,하지만 좋은 오래된 명명 규칙을 사용해야합니다.
declare @MY_VALUE as int
T-SQL에는 상수에 대한 기본 제공 지원이 없습니다. SQLMenace의 접근 방식을 사용하여 시뮬레이션하거나 (다른 사람이 다른 것을 반환하기 위해 함수를 덮어 썼는지 여부를 확신 할 수는 없지만…) 여기에서 제안한대로 상수를 포함하는 테이블을 작성할 수 있습니다 . ConstantValue
열에 대한 변경 사항을 롤백하는 트리거를 작성할 수 있습니까?
SQL 함수를 사용하기 전에 다음 스크립트를 실행하여 성능 차이를 확인하십시오.
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
변수 값에 대한 최적의 실행 계획을 얻으려면 동적 SQL 코드를 사용할 수 있습니다. 변수를 일정하게 만듭니다.
DECLARE @var varchar(100) = 'some text'
DECLARE @sql varchar(MAX)
SET @sql = 'SELECT * FROM table WHERE col = '''+@var+''''
EXEC (@sql)
열거 형 또는 단순 상수의 경우 단일 행이있는 뷰는 성능이 뛰어나고 컴파일 시간 검사 / 종속성 추적 (열 이름이 발생 함)이 있습니다.
Jared Ko의 블로그 게시물 https://blogs.msdn.microsoft.com/sql_server_appendix_z/2013/09/16/sql-server-variables-parameters-or-literals-or-constants/ 참조
보기 만들기
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]
보기 사용
SELECT h.*
FROM Sales.SalesOrderHeader
WHERE ShipMethodID = ( select [OVERNIGHT J-FAST] from ShipMethods )
좋아, 보자
상수는 컴파일 시간에 알려지고 프로그램 수명 동안 변경되지 않는 변경 불가능한 값입니다.
즉, SQL Server에서 상수를 가질 수 없습니다.
declare @myvalue as int
set @myvalue = 5
set @myvalue = 10--oops we just changed it
방금 변경된 값
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.
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
참고URL : https://stackoverflow.com/questions/26652/is-there-a-way-to-make-a-tsql-variable-constant
'IT박스' 카테고리의 다른 글
인증서는 PC에서 신뢰하지만 Android에서는 신뢰하지 않습니다. (0) | 2020.10.08 |
---|---|
Maven : 확인할 수없는 상위 POM (0) | 2020.10.08 |
가장 좋아하는 프로파일 링 도구는 무엇입니까 (C ++ 용) (0) | 2020.10.08 |
자바 메소드 인수를 최종으로 만들기 (0) | 2020.10.07 |
jQuery-UI의 자동 완성이 제대로 표시되지 않음, Z- 색인 문제 (0) | 2020.10.07 |