0

我想在我的 SP 中将 PassColumn 名称作为参数如果我的 tat 列存在于第一个表(Batch_Master)中,想从该列中获取值,

如果该列存在于我的第二个表(GTIN_Master)中,想从 tat 表列中获取值,每个表都有类似的列.. Batch_Master (Batch_M_id, GTIN(primary key),....etc GTIN_Master (GTIN (foreign key) ),..ETC)

我有Batch_M_id列名作为参数..

注意:列名称具有随机数据类型、某个时间 int 或某个时间 datetime 等

我尝试跟随 SP

CREATE PROCEDURE dbo.StoredProcedure2

    @columnName varchar(50),
    @batchmId  int
AS

if exists(select * from sys.columns 
            where Name = N'columnName' and Object_ID = Object_ID(NBatch_Master'))    

begin

select @columnName from Batch_Master

end


else

begin

 select @columnName 
     from GTIN_Master inner join Batch_Master
     on GTIN_Master.GTIN = Batch_Master.GTIN
     where Batch_M_id =@batchmId


    end
    RETURN
4

3 回答 3

1

当您不确切知道要执行的查询结构时,您需要什么,那么您必须创建一个动态查询,这实际上是模板查询的一种形式。

CREATE PROCEDURE dbo.StoredProcedure2

    @columnName varchar(50),
    @batchmId  int
AS

    DECLARE @SQL1 AS VARCHAR(MAX)
    DECLARE @SQL2 AS VARCHAR(MAX)

    SET @SQL1 = 'select ' + @columnName + ' from Batch_Master'

    SET @SQL1 = 'select ' + @columnName + '
         from GTIN_Master inner join Batch_Master
         on GTIN_Master.GTIN = Batch_Master.GTIN
         where Batch_M_id =' + CONVERT(VARCHAR,@batchmId)

    IF EXISTS(SELECT * FROM sys.columns WHERE Name = @columnName and Object_ID = Object_ID(N'Batch_Master'))
        BEGIN    
            EXEC (@SQL1)
        END
    ELSE
        BEGIN
            EXEC (@SQL2)
        END

以上将做你想要的,但容易出错。例如,如果参数中传递的列在第二个查询中使用的表中不存在怎么办?在第二种情况下,您可能还需要检查是否存在。

于 2013-09-06T07:08:11.447 回答
0
DECLARE @SQL VARCHAR(MAX)
SET @SQL = 'select ' + @columnName + ' from Batch_Master'

EXECUTE(@SQL)
于 2013-09-06T07:07:44.163 回答
0

这个 SQL:

set nocount on
go

create table One (id int, name varchar(25))
go
create table Two (id int, value varchar(25))
go

insert into One values (1, 'Table One')
insert into Two values (1, 'Table Two')
go

create procedure sp_test_colname
  @colname sysname
as
  declare @sql nvarchar(2048)

  if exists (select 1 from sys.columns where name = @colname and object_id = object_id(N'One'))
    set @sql = 'select [' + @colname + '] from [One]'
  else
    if exists (select 1 from sys.columns where name = @colname and object_id = object_id(N'Two'))
      set @sql = 'select [' + @colname + '] from [Two]'

  if @sql <> ''
    exec sp_executesql @sql
go

exec sp_test_colname 'name'
exec sp_test_colname 'value'
exec sp_test_colname 'somethingelse'
go

drop procedure sp_test_colname
drop table One, Two

返回以下内容:

name
-------------------------
Table One

value
-------------------------
Table Two
于 2013-09-06T07:20:56.203 回答