将列名称作为参数传递

时间:2013-09-06 06:57:22

标签: c# sql stored-procedures

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

如果该列存在于我的第二个表(GTIN_Master)中,想要从tat表列中获取值, 每个表都有像... Batch_Master(Batch_M_id,GTIN(主键),等等 GTIN_Master(GTIN(外键),..等)

我有 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

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

DECLARE @SQL VARCHAR(MAX)
SET @SQL = 'select ' + @columnName + ' from Batch_Master'

EXECUTE(@SQL)

答案 2 :(得分: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