Question : Stored Procedure with optional parameter

Hi,

I doing my first steps with the SQL Server and I like to use a stored procedure with optional parameter.
So what I need is to select data from a table and if the year parameter is given the condition is the given year, else the current.
With the month is the same if the parameter is given us it and else the current one.
If there's no IP given every IP should be selected.

I tried by myself but this seems to be the wrong way...
Can somebody help me making this work plese?

Thanks

Andre
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetDatas] 
(
	@Year	int = NULL
	,@Month int = NULL
	,@IP	varchar(20) = '%'
)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @sql nvarchar (4000)

	SELECT @sql = 'SELECT * FROM InternetLog WHERE s-ip LIKE ''@IP'''
	
	IF @Year IS NULL
		SELECT @sql = @sql + ' AND YEAR(logdate) = YEAR(GETDATE())'
	ELSE
		SELECT @sql = @sql + ' AND YEAR(logdate) = @Year'

	IF @Month IS NULL
		SELECT @sql = @sql + ' AND MONTH(logdate) = MONTH(GETDATE())'
	ELSE
		SELECT @sql = @sql + ' AND MONTH(logdate) = @Month'
		
	SELECT @sql = @sql + ' ORDER BY logdate ASC'
	
	Exec @sql
END

Answer : Stored Procedure with optional parameter

With any instance (line 4) :

1:
2:
3:
4:
5:
6:
7:
8:
<html><head></head><body>
<script language="javascript">
	var mystring = "hello world this is a string";
	var startBy = "str";
	var r = new RegExp( startBy + "\\w*\\s*" );
	alert( r.exec(mystring) );
</script>
</body></html>
Random Solutions  
 
programming4us programming4us