有没有办法在变速器中保持变量?
Declare @bob as varchar(50);
Set @bob = 'SweetDB';
GO
USE @bob --- see note below
GO
INSERT INTO @bob.[dbo].[ProjectVersion] ([DB_Name], [Script]) VALUES (@bob,'1.2')
请参阅此SO问题,了解“USE @bob”行。
答案 0 :(得分:101)
使用临时表:
CREATE TABLE #variables
(
VarName VARCHAR(20) PRIMARY KEY,
Value VARCHAR(255)
)
GO
Insert into #variables Select 'Bob', 'SweetDB'
GO
Select Value From #variables Where VarName = 'Bob'
GO
DROP TABLE #variables
go
答案 1 :(得分:29)
go
命令用于将代码分成不同的批次。如果这正是您想要做的,那么您应该使用它,但这意味着批次实际上是分开的,并且您不能在它们之间共享变量。
在您的情况下,解决方案很简单;您可以删除go
语句,该代码中不需要它们。
附注:您不能在use
语句中使用变量,它必须是数据库的名称。
答案 2 :(得分:12)
我更喜欢这个问题的this答案 Global Variables with GO
除了能够做你原本想做的事情之外,还有其他好处。
需要注意的是,您需要打开SQLCMD模式(在Query-> SQLCMD下)或默认情况下为所有查询窗口打开它(工具 - >选项然后查询结果 - >默认情况下,打开新查询在SQLCMD模式下)
然后你可以使用以下类型的代码(Oscar E. Fraxedas Tormo完全从相同的答案中删除)
--Declare the variable
:setvar MYDATABASE master
--Use the variable
USE $(MYDATABASE);
SELECT * FROM [dbo].[refresh_indexes]
GO
--Use again after a GO
SELECT * from $(MYDATABASE).[dbo].[refresh_indexes];
GO
答案 3 :(得分:1)
不确定,如果这有帮助
declare @s varchar(50)
set @s='Northwind'
declare @t nvarchar(100)
set @t = 'select * from ' + @s + '.[dbo].[Customers]'
execute sp_executesql @t
答案 4 :(得分:1)
如果您使用的是SQL Server,则可以为整个脚本设置全局变量,例如:
:setvar sourceDB "lalalallalal"
稍后在脚本中使用:
$(sourceDB)
确保在Server Managment Studi中启用SQLCMD模式,您可以通过顶级菜单单击查询并切换SQLCMD模式。
有关主题的更多信息,请访问: MS Documentation
答案 5 :(得分:0)
临时表保留在GO语句上,所以......
SELECT 'value1' as variable1, 'mydatabasename' as DbName INTO #TMP
-- get a variable from the temp table
DECLARE @dbName VARCHAR(10) = (select top 1 #TMP.DbName from #TMP)
EXEC ('USE ' + @dbName)
GO
-- get another variable from the temp table
DECLARE @value1 VARCHAR(10) = (select top 1 #TMP.variable1 from #TMP)
DROP TABLE #TMP
它不漂亮,但它有效
答案 6 :(得分:0)
创建自己的存储过程,该过程将保存/加载到临时表中。
MyVariableSave -- Saves variable to temporary table.
MyVariableLoad -- Loads variable from temporary table.
然后您可以使用此:
print('Test stored procedures for load/save of variables across GO statements:')
declare @MyVariable int = 42
exec dbo.MyVariableSave @Name = 'test', @Value=@MyVariable
print(' - Set @MyVariable = ' + CAST(@MyVariable AS VARCHAR(100)))
print(' - GO statement resets all variables')
GO -- This resets all variables including @MyVariable
declare @MyVariable int
exec dbo.MyVariableLoad 'test', @MyVariable output
print(' - Get @MyVariable = ' + CAST(@MyVariable AS VARCHAR(100)))
输出:
Test stored procedures for load/save of variables across GO statements:
- Set @MyVariable = 42
- GO statement resets all variables
- Get @MyVariable = 42
您也可以使用这些:
exec dbo.MyVariableList -- Lists all variables in the temporary table.
exec dbo.MyVariableDeleteAll -- Deletes all variables in the temporary table.
exec dbo.MyVariableList
的输出:
Name Value
test 42
事实证明,能够列出表中的所有变量实际上是非常有用的。因此,即使您以后不加载变量,它也非常适合调试目的,以便在一处查看所有内容。
这使用前缀为##
的临时表,因此足以保留GO语句。它旨在在单个脚本中使用。
和存储过程:
-- Stored procedure to save a variable to a temp table.
CREATE OR ALTER PROCEDURE MyVariableSave
@Name varchar(255),
@Value varchar(MAX)
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON
IF NOT EXISTS (select TOP 1 * from tempdb.sys.objects where name = '##VariableLoadSave')
BEGIN
DROP TABLE IF EXISTS ##VariableLoadSave
CREATE TABLE ##VariableLoadSave
(
Name varchar(255),
Value varchar(MAX)
)
END
UPDATE ##VariableLoadSave SET Value=@Value WHERE Name=@Name
IF @@ROWCOUNT = 0
INSERT INTO ##VariableLoadSave SELECT @Name, @Value
END
GO
-- Stored procedure to load a variable from a temp table.
CREATE OR ALTER PROCEDURE MyVariableLoad
@Name varchar(255),
@Value varchar(MAX) OUT
WITH EXECUTE AS CALLER
AS
BEGIN
IF EXISTS (select TOP 1 * from tempdb.sys.objects where name = '##VariableLoadSave')
BEGIN
IF NOT EXISTS(SELECT TOP 1 * FROM ##VariableLoadSave WHERE Name=@Name)
BEGIN
declare @ErrorMessage1 as varchar(200) = 'Error: cannot find saved variable to load: ' + @Name
raiserror(@ErrorMessage1, 20, -1) with log
END
SELECT @Value=CAST(Value AS varchar(MAX)) FROM ##VariableLoadSave
WHERE Name=@Name
END
ELSE
BEGIN
declare @ErrorMessage2 as varchar(200) = 'Error: cannot find saved variable to load: ' + @Name
raiserror(@ErrorMessage2, 20, -1) with log
END
END
GO
-- Stored procedure to list all saved variables.
CREATE OR ALTER PROCEDURE MyVariableList
WITH EXECUTE AS CALLER
AS
BEGIN
IF EXISTS (select TOP 1 * from tempdb.sys.objects where name = '##VariableLoadSave')
BEGIN
SELECT * FROM ##VariableLoadSave
ORDER BY Name
END
END
GO
-- Stored procedure to delete all saved variables.
CREATE OR ALTER PROCEDURE MyVariableDeleteAll
WITH EXECUTE AS CALLER
AS
BEGIN
DROP TABLE IF EXISTS ##VariableLoadSave
CREATE TABLE ##VariableLoadSave
(
Name varchar(255),
Value varchar(MAX)
)
END
答案 7 :(得分:0)
如果只需要二进制“是/否”(例如是否存在列),则可以使用SET NOEXEC ON
禁用语句的执行。 SET NOEXEC ON
适用于GO(跨批次)。但是记住在脚本末尾使用SET NOEXEC OFF
重新打开EXEC 。
IF COL_LENGTH('StuffTable', 'EnableGA') IS NOT NULL
SET NOEXEC ON -- script will not do anything when column already exists
ALTER TABLE dbo.StuffTable ADD EnableGA BIT NOT NULL CONSTRAINT DF_StuffTable_EnableGA DEFAULT(0)
ALTER TABLE dbo.StuffTable SET (LOCK_ESCALATION = TABLE)
GO
UPDATE dbo.StuffTable SET EnableGA = 1 WHERE StuffUrl IS NOT NULL
GO
SET NOEXEC OFF
这将编译语句,但不执行它们。因此,如果引用不存在的架构,您仍然会遇到“编译错误”。因此它可以“关闭”第二次运行的脚本(我在做什么),但无法在第一次运行时关闭脚本的某些部分,因为如果引用不这样做的列或表,仍然会出现编译错误还不存在。
答案 8 :(得分:0)
您可以按照以下步骤使用NOEXEC:
创建表格
#temp_procedure_version(procedure_version varchar(5),pointer varchar(20))
将过程版本和指向该版本的指针插入到临时表#temp_procedure_version
-procedure_version指针示例
插入temp_procedure_version
值(1.0,“第一个版本”)
插入temp_procedure_version
值(2.0,“最终版本”)
然后获取过程版本,可以使用以下语句中的where条件
从@ProcedureVersion=ProcedureVersion
中选择#temp_procedure_version
,其中
pointer='first version'
IF (@ProcedureVersion='1.0')
BEGIN
SET NOEXEC OFF --code execution on
END
ELSE
BEGIN
SET NOEXEC ON --code execution off
END
-在此处插入过程版本1.0
以.....创建程序版本1.0。
SET NOEXEC OFF -- execution is ON
从@ProcedureVersion=ProcedureVersion
中选择#temp_procedure_version
,其中
指针=“最终版本”
IF (@ProcedureVersion='2.0')
BEGIN
SET NOEXEC OFF --code execution on
END
ELSE
BEGIN
SET NOEXEC ON --code execution off
END
将过程版本2.0创建为.....
SET NOEXEC OFF -- execution is ON
-删除临时表
拖放表格#temp_procedure_version