SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SiteSettings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SiteSettings_Get]
GO


CREATE  PROCEDURE [dbo].cs_SiteSettings_Get
(
	@SiteUrl nvarchar(512) = null,
	@SettingsID int = 0,
	@ReturnAll bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

If @ReturnAll = 0
Begin
Select 
		top 1 ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss
		LEFT OUTER JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		LEFT OUTER JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		ORDER BY ss.SettingsID asc

End

ELSE IF @SiteUrl is null
Begin
Select 
		ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss
		LEFT OUTER JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		LEFT OUTER JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			ss.SettingsID = @SettingsID
End
Else
Begin
	IF @SiteUrl = '*'
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
	
	ELSE IF NOT EXISTS (SELECT * FROM cs_Sites WHERE SiteUrl = @SiteUrl OR SiteUrl = @SiteUrl + '/')
		RETURN
	ELSE
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			(s.SiteUrl = @SiteUrl OR s.SiteUrl = @SiteUrl + '/')
End

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SiteSettings_Get to public
go