读书人

如何在SQL语句中动态处理表名

发布时间: 2012-09-08 10:48:07 作者: rapoo

怎么在SQL语句中动态处理表名?
表tb中有一列为type,char(1),
比如type可能为A,语句想完成的功能为select tb.*,(select count(*) from type_A where ...) as 数量 ,怎么将type_A替换为动态的类似type_ + tb.type

[解决办法]
这个需要动态拼接SQL语句

exec('动态拼接的语句')
[解决办法]

SQL code
-->trycreate table tb(f1 int,type varchar(1))insert into tbselect 1,'A' union allselect 2,'B' union allselect 3,'C'create table type_A(col1 int)insert into type_Aselect 1 union allselect 2create table type_B(col1 int)insert into type_Bselect 1 union allselect 2create table type_C(col1 int)insert into type_Cselect 1 union allselect 2godeclare @sql varchar(4000)select @sql=isnull(@sql+' union all ','')+'select count(*) as cnt,'''+type+''' as type from type_'+typefrom tbset @sql='select tb.*,t.cnt from tb,('+@sql+')t where tb.type=t.type'--print @sqlexec(@sql)/*f1          type cnt----------- ---- -----------1           A    22           B    23           C    2*/ 

读书人网 >SQL Server

热点推荐