可以创建一个具有列名的临时表,其中列名是另一个表的主键。例如...
table a
column1 (pk)
column2
column3
column4 (pk)
column5
临时表如下:
#table temp
column1
column4
...因此仅使用表a中的主键列 代码如何? 谢谢
答案 0 :(得分:1)
您可以使用动态sql
declare @sql nvarchar(1000) = '';
declare @col_list nvarchar(100) = '';
;with
n as (
select tc.name, tc.column_id
from sys.indexes i
join sys.index_columns ic on i.object_id = ic.object_id and i.index_id = ic.index_id
join sys.columns tc on i.object_id = tc.object_id and tc.column_id = ic.column_id
where i.object_id = OBJECT_ID('table_a')
and i.is_primary_key = 1
)
select @col_list = substring((select ', ' + CAST(quotename(name) AS NVARCHAR(128)) [*]
from n
order by column_id
for xml path('')), 2, 9999)
set @sql = 'select ' + @col_list + ' into ##table_temp from table_a where 1=0'
print @sql;
exec sp_executesql @sql
select * from ##table_temp
答案 1 :(得分:0)
是的,那是可能的。临时表不在乎您要提供给他的值是否是原始表上的主键。
编辑:
要回答您所编辑的问题:
create table #temptable
(
column1values datatype,
column4values datatype
)
insert into #temptable
select column1, column4 from a
答案 2 :(得分:0)
以下代码将帮助您,但 sp_executesql 语句在另一个会话中创建临时表,因此,您可以使用全局临时表。
func checkLocationAuthorization() {
switch CLLocationManager.authorizationStatus(){
case .authorizedWhenInUse:
mapView.showsUserLocation = true
centerViewOnUserLocation()
default:
break
}
}