【发布时间】:2012-09-10 23:55:02
【问题描述】:
我有以下创建视图的存储过程:
ALTER PROC Proc_Guards_By_Client
(
@client_number INT,
@client_name NVARCHAR(16)
)
AS
BEGIN
IF EXISTS(select * FROM sys.views where name = 'vwGuardsByClients')
BEGIN
EXEC ('CREATE VIEW vwGuardsByClients
AS
SELECT TOP 1000
cgt.[guard_id],
sg.first_name,
sg.last_name,
sg.ammunition_quantity
FROM [sws4].[dbo].[client_guard_tracking] cgt
INNER JOIN CLIENTS c
ON c.client_number = cgt.client_number
INNER JOIN security_guard sg
ON sg.guard_id = cgt.guard_id
WHERE cgt.client_number = @client_number
OR c.client_name = @client_name
')
END
ELSE
BEGIN
EXEC ('UPDATE VIEW vwGuardsByClients
SELECT TOP 1000
cgt.[guard_id],
sg.first_name,
sg.last_name,
sg.ammunition_quantity
FROM [sws4].[dbo].[client_guard_tracking] cgt
INNER JOIN CLIENTS c
ON c.client_number = cgt.client_number
INNER JOIN security_guard sg
ON sg.guard_id = cgt.guard_id
WHERE cgt.client_number = @client_number
OR c.client_name = @client_name
')
END
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated'
END
但是当我执行它时,我得到:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'VIEW'.
Msg 137, Level 15, State 2, Line 14
Must declare the scalar variable "@client_number".
【问题讨论】:
-
这里为什么使用动态SQL?
-
这是使用存储过程创建/更新视图的要求
-
@abatishchev 你试过了吗?你不能在过程中调用
CREATE VIEW。 -
这仍然是倒退。你的逻辑说:“如果视图存在,创建它!如果它不存在,编辑它!”另外我不知道你从哪里学到的语法“UPDATE VIEW”——它应该是“ALTER VIEW”。
-
“这是使用存储过程创建/更新视图的要求” - 这不是要求。某人决定的解决方案的一部分是“正确”的事情。如果您告诉我们要解决的原始问题是什么,而不是这个解决方案的问题,我们会做得更好。
标签: sql-server-2008 tsql stored-procedures dynamic-sql sql-view