我想编写一个以@FirmId为参数的存储过程,我将根据此参数使用相关表。
我想要获得的(但我不想使用)是这样的:
CREATE PROCEDURE spFirmDetailGetByFirmId
@FirmId AS INT
AS
BEGIN
IF @FirmId = 1
SELECT * FROM Firm1
ELSE IF @FirmId = 2
SELECT * FROM Firm2
.
.
.
.
ELSE IF @FirmId = 1000
SELECT * FROM Firm1000
END
而且我也不想创建查询字符串然后执行EXEC,就像在下面的代码块中那样。因为真正的查询过于复杂,如果我使用此选项将很难管理。
CREATE PROCEDURE spFirmDetailGetByFirmId
@FirmId AS INT
AS
BEGIN
DECLARE @Query AS NVARCHAR(MAX) = 'SELECT * FROM Firm'
SET @Query = @Query + CAST(@FirmId AS NVARCHAR(10))
EXEC(@Query)
END
还有其他选择吗? 感谢。
答案 0 :(得分:3)
我带你的是表格是相同的并且将保持相同以建议两种方法:
DECLARE @Firm VARCHAR(10)='Firm3';
SELECT * FROM Firm1 WHERE @Firm='Firm1'
UNION ALL
SELECT * FROM Firm2 WHERE @Firm='Firm2'
UNION ALL
SELECT * FROM Firm3 WHERE @Firm='Firm3'
[...]
UNION ALL
SELECT * FROM Firm1000 WHERE @Firm='Firm1000'
第二个是:
DECLARE @query NVARCHAR(MAX)='SELECT * FROM ####';
SET @query=REPLACE(@query,'####',@Firm);
EXEC (@query)
第二个可以与VIEW
(代替@query
)一起使用,您可以在其中将VIEW的定义读入变量并创建ALTER VIEW
- 动态声明...你的程序将调用相同的VIEW(但这会因并行调用而崩溃!)
答案 1 :(得分:1)
此代码可以通过在存储过程中使用来自动创建视图,每次需要添加列
declare @tableId int
declare @columns varchar(max)
declare @tablesCount int
declare @tableName varchar(255)
declare @query varchar(255)
declare @id int
declare @result nvarchar(max)
set @columns = ''
set @tableName = 'Firm'
set @id = 1
set @result = ''
--Base table
select @tableId = object_id from sys.tables where name =@tableName
--Count how many table with the 'same name'
select @tablesCount= count(*) from sys.tables where name like @tableName+'%'
--Build Columns to add in the view
select @columns =@columns+name+', 'from Sys.columns where object_id = @tableId
--Drop View
set @result = 'Drop view vw_'+@tableName
exec sp_executesql @result
set @result=''
while(@id<=@tablesCount)
Begin
declare @idVarchar varchar(10)
set @idVarchar = cast(@id as varchar(10))
set @result =@result+'Select '+@columns+@idVarchar+' as FirmId from '+@tableName+@idVarchar
+'
Union all
'
set @id =@id+1
End
set @result = substring(@result, 1, len(@result)-12)
set @result='Create view vw_'+@tableName+' as
'+@result
exec sp_executesql @result
还有另一种选择,你也可以使用sp_helpText来获取视图的当前定义,并仅追加添加新表标识符