表名用变量装起来,该如何处理
表名用变量装起来
前面的代码就不贴了!
@v_form = 表名
declare @v_form varchar(100)
IF ( @export_type = 1 ) --1 出口查询 2转厂查询
begin
set @v_form = 'ni_contract_export_find_vd'
end
else
set @v_form = 'ni_contract_export_find_vt' --这个我赋值的语句
SELECT leave_num,
seq_no,
num,
description,
box_number,
cust_name,
cust_number,
leave_id,
creation_date,
order_number,
out_type,
x_id,
x_weight
FROM @v_form --这行会报错 :Must declare the variable '@v_form'.
end
go
请帮忙看看,最好可以解释下 我哪里出错了
------解决方案--------------------
用字符串拼接,因为你那样用是字符串,不是表对象
前面的代码就不贴了!
@v_form = 表名
declare @v_form varchar(100)
IF ( @export_type = 1 ) --1 出口查询 2转厂查询
begin
set @v_form = 'ni_contract_export_find_vd'
end
else
set @v_form = 'ni_contract_export_find_vt' --这个我赋值的语句
SELECT leave_num,
seq_no,
num,
description,
box_number,
cust_name,
cust_number,
leave_id,
creation_date,
order_number,
out_type,
x_id,
x_weight
FROM @v_form --这行会报错 :Must declare the variable '@v_form'.
end
go
请帮忙看看,最好可以解释下 我哪里出错了
------解决方案--------------------
用字符串拼接,因为你那样用是字符串,不是表对象
DECLARE @tableName VARCHAR(100)
SET @tableName ='SaleMst'
DECLARE @sql NVARCHAR(4000)
SET @sql=N'select * from '+@tableName+''
EXEC(@sql)