我想声明一个变量并执行以下操作:
Select
cast (SUM(case when @Dummy is not null then 1 else 0 end)*1.0/443321 as decimal(10,5)) @Dummy
FROM hellotable
WHERE @Dummy in ("100 different field names in hellotable")
但是,这不起作用...任何帮助表示赞赏。
我想声明一个变量并执行以下操作:
Select
cast (SUM(case when @Dummy is not null then 1 else 0 end)*1.0/443321 as decimal(10,5)) @Dummy
FROM hellotable
WHERE @Dummy in ("100 different field names in hellotable")
但是,这不起作用...任何帮助表示赞赏。
尝试使用临时表来填充这些数据,然后使用主表进行用户内部联接,而不是在 WHERE 子句中使用 IN。
CREATE TABLE #TempTable (FieldFromHelloTable nvarchar(50))
INSERT INTO #TempTable
VALUES ('value1'),('value2'),('value3'),('value4'),('value5')
SELECT * --this is oversimplified to ilustrate the point and you can modify this further
FROM HelloTable H
inner join #TempTable Tmp on H.SomeField = Tmp.FieldFromHelloTable
尝试通过动态 SQL 来做到这一点。
DECLARE @dummy sysname
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = 'SELECT CAST (SUM(CASE WHEN '+ @Dummy +N' IS NOT NULL THEN 1
ELSE 0
END) * 1.0 / 443321 AS DECIMAL(10, 5)) '+ @Dummy +N'
FROM hellotable
WHERE '+ @Dummy +N' IN ( '' )'
EXEC (@SQL)