我正在尝试从一行中选择数据,然后使用该值将另一个预定义数据值输入到变量中。我有这个,不知道它是否是SQL的正确语法。
DECLARE @ID INT
DECLARE @server VARCHAR(15)
DECLARE response_cursor CURSOR
FOR SELECT col1, col3, col4 FROM [dbo].[tbl] WHERE [status] <> 'Decommission'
IF col3 ='ABCD'
THEN @server = 'Server1';
ELSIF col3 ='DEFS'
THEN @server = 'Server2';
ELSIF col3 ='THSE'
THEN @server = 'Server3';
...
ELSE col3 = NULL
THEN @server = Null
END IF;
当我尝试运行它时,我得到了这个:
消息156,级别15,状态1,行9关键字附近的语法不正确 '然后'。
这是在MS SQL 2012服务器上运行
这是我正在处理的整个sql语句;可能有助于更好地解释我正在尝试做什么。
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[sp_anotherprocedure]
as
begin
-- begin loop processing to get a response for each record in the validation table
DECLARE @ID INT
DECLARE @server varchar(15)
DECLARE @port nvarchar(5)
declare response_cursor cursor
for select ID, COL3, Assigned_Port from [dbo].[tbl] where [Status] <> 'Decommission' -- we dont want to process decommissioned ports
if COL3='123'
begin @server = 'ABC'; end
IF COL3='456'
begin @server = 'DEF'; end
IF COL3='789'
begin @server = 'HIJ'; end
ELSE COL3 = NULL
begin @server = '' END
open response_cursor
fetch next from response_cursor -- get the first record
INTO @ID, @SERVER, @PORT
WHILE @@FETCH_STATUS = 0
BEGIN
-- make the call
DECLARE @RC int
DECLARE @request nvarchar(100)
DECLARE @out nvarchar(max)
--set @server = 'xxx.xxx.xxx.xxx' --ip address of the server
--set @port = '101010' --port of the server
set @request = '"some_parmamet'
EXECUTE @RC = [dbo].[sp_stored]
@server
,@port
,@request
,@out output
-- UPDATE THE RESPONSE FIELD FOR THE CURRENT RECORD WITH THE RESPONSE FROM THE REQUEST
/* UPDATE [dbo].[tbl]
set response = @out
where ID = @ID
fetch next from response_cursor -- get the next record and repeat request
into @ID, @SERVER, @PORT
*/
Print @out
END
close response_cursor
deallocate response_cursor
end
答案 0 :(得分:1)
这里有几个问题:
.Select
第一次
DECLARE @ID INT
DECLARE @server VARCHAR(15)
DECLARE response_cursor CURSOR
FOR SELECT col1, col3, col4 FROM [dbo].[tbl] WHERE [status] <> 'Decommission'
我所知道的SQL中没有ELSE / IF。
IF col3 ='ABCD'
BEGIN SET @server = 'Server1'; END
Yuu不需要END IF。你为每个IF做一个BEGIN / END。此外,如果您需要,您可以使用ELSE
结构是
IF col3 ='DEFS'
BEGIN SET @server = 'Server2'; END
IF col3 ='THSE'
BEGIN SET @server = 'Server3'; END
如果你真的需要使用IF / THEN / ELSE模型,你可以随时使用CASE
那个结构是
IF something BEGIN dosomething END
ELSE
BEGIN doSomethingElse END
答案 1 :(得分:1)
您可以使用CASE
语句获得更清晰的代码。
SELECT @server = (
CASE col3
WHEN '123' THEN 'ABC'
WHEN '456' THEN 'DEF'
WHEN '789' THEN 'GHI'
ELSE ''
END)
答案 2 :(得分:0)
CASE
WHEN col3 = 'ABCD' THEN 'Server1'
WHEN col3 = 'DEFS' THEN 'Server2'
WHEN col3 = 'THSE' THEN 'Server3'
ELSE NULL END as @server