以下是我的SQL查询。它包含变量,所以我想它不能另存为VIEW。如何使它与“功能” /“存储过程/视图”一起使用?
DECLARE @sql varchar(max);
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') +
'SELECT * FROM ' + QuoteName(DatabaseName) + '.dbo.states'
FROM sanketuniversal.dbo.databasemaster
where itemdata = 0 and CustomerGroupfordisplay = 1;
--PRINT @sql
EXEC (@sql);
另一个选项是功能。我也尝试过但出现错误。
CREATE FUNCTION dbo.MNReport()
RETURNS @MN_table TABLE (
SIDs VARCHAR(MAX) NOT NULL,
StateName VARCHAR(20) NOT NULL
)
AS
BEGIN
DECLARE @sql varchar(max);
INSERT INTO @MN_table
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') +
'SELECT count(*) FROM ' + QuoteName(DatabaseName) + '.dbo.states'
FROM sanketuniversal.dbo.databasemaster
where itemdata = 0 and CustomerGroupfordisplay = 1;
RETURN;
END;
错误:“ INSERT语句不能包含将值分配给变量的SELECT语句”