sql server - Multiple SQL or Case statements in Scalar function -
i struggling sql function report writing. function polls audit table original value of particular field (secondaryschoolcode). if finds value in audit table current row should return value, if there no value current row original parameter supplied function should returned instead. have tried using case statement not returning parameter if there no match in audit table. suggestions on how accomplish this?
alter function [dbo].[fn_auditoriginalhsattendingcode] ( @studentid varchar(255), @secondaryschoolcode varchar(255), @columnname varchar(255) ) returns varchar(255) begin declare @result varchar(255); return (select top (1) case when @columnname <> 'secondaryschoolcode' @secondaryschoolcode else dbo.gdsauditdetail.valuebeforechange end dbo.gdsauditdetail inner join dbo.studentschool inner join dbo.student on dbo.studentschool.studentid = dbo.student.id inner join dbo.secondaryschool on dbo.studentschool.secondaryschoolid = dbo.secondaryschool.id inner join dbo.gdsaudit on dbo.student.id = dbo.gdsaudit.entityid on dbo.gdsauditdetail.gdsauditid = dbo.gdsaudit.id (dbo.student.id = @studentid) , dbo.gdsauditdetail.gdscolumn='secondaryschoolcode' order dbo.gdsaudit.inserteddate asc)
the call function looks this:
dbo.fn_auditoriginalhsattendingcode(dbo.student.id , dbo.secondaryschool.secondaryschoolcode , dbo.gdsauditdetail.gdscolumn)
i'm not sure of relationships are, based on stated requirements , current query, joining tables don't need. reason don't when audit doesn't exist because there no rows select top 1
. should return @ least 1 row existing student.
select top (1) isnull(dbo.gdsauditdetail.valuebeforechange, @secondaryschoolcode) dbo.student left join dbo.gdsaudit on dbo.student.id = dbo.gdsaudit.entityid left join dbo.gdsauditdetail on dbo.gdsauditdetail.gdsauditid = dbo.gdsaudit.id , dbo.gdsauditdetail.gdscolumn='secondaryschoolcode' (dbo.student.id = @studentid) order dbo.gdsaudit.inserteddate asc
Comments
Post a Comment