使用@columnsname = ID
时显示错误,@columnsname = [address]
显示返回值0不显示我想修复错误帮助查询的数据。
查询:
create procedure ProcedureName1
(@columnsname sysname, --varchar(50)
@columnsvalue varchar(50)
)
as
begin
declare @sql nvarchar(max), @column_name sysname;
/* make sure the @columnsname is a valid column name */
set @column_name = (select c.name
from sys.columns c
where c.object_id = object_id(N'Tabl1')
and c.name = @columnsname);
set @sql = 'with cte as (
select
ID
, names
, null as address
, work
, note
from Tabl1
where '+@column_name+' like @columnsvalue
union all
select
t2.ID
, t2.name
, t2.address
, null
, null as tt
from Tabl2 as t2
left join Tabl1 as t1 on t2.ID = t1.ID
where '+@column_name+' like @columnsvalue
)
select *
from cet
order by
id
, note desc
, address;'
exec sp_executesql @sql, N'@columnsvalue varchar(50)', @columnsvalue
end;
go
我收到以下错误:
Msg 209,Level 16,State 1,Line 21
不明确的列名称' ID'
答案 0 :(得分:0)
你几乎已经在SQL语句中回答了这个问题。
当您连接两个具有共同列名的表时,您将创建一个重复列名称的情况。如果您要求该列名称,那么它将是不明确的,因为SQL可以从每个表中进行选择,并且它不会猜测。
解决方案是在SELECT语句中使用格式table.column
。在您的情况下,使用Tabl1.id
或t1.id
,具体取决于您是否使用表别名。
答案 1 :(得分:0)
错误是由此语句(联合查询的第二部分)
引起的where ' + @column_name + ' like @columnsvalue
如果@column_name = 'ID'
该查询将是
select
t2.ID
, t2.name
, t2.address
, null
, null as tt
from Tabl2 as t2
left join Tabl1 as t1 on t2.ID = t1.ID
where ID like @columnsvalue
列ID
将不明确