打印选定值

Print selected values

如果有几个表,我想从这些表中找出col2为null时col1的值,并通过存储过程打印这些值。

col1 col2
一个 一个
b
b B
c C
一个

预期输出: a,b

--what I did but can not work

create proc sp_getValue
@tableName varchar(30)
as
declare @result nvarchar(max)
select distinct col1=@result from @tableName
print @result

感谢您的帮助。

如果你想得到 table 名字作为参数,你应该使用 exec.

create proc sp_getValue
 @tableName varchar(30)
as
  exec('select distinct col1 from '+ quotename(@tableName) + ' where col2 is null'); 

要将此 table 转换为字符串,您可以将结果输出到某个临时文件 table 中,然后使用游标遍历它。像这样:

DECLARE @value  NVARCHAR(30)
DECLARE @result NVARCHAR(100) = '';
CREATE TABLE #temp
(
    col1 NVARCHAR(30)
)

EXEC ('insert into #temp select col1 from ' + @tableName +' where col2 is null')

DECLARE myCur CURSOR FOR SELECT *
                         FROM #temp;
open myCur;
FETCH next from myCur  INTO @value;

WHILE @@FETCH_STATUS = 0
    BEGIN
        set @result = @result + @value + ',';
        FETCH next from myCur INTO @value;
    END

PRINT @result

close myCur;
DEALLOCATE myCur;