Pass a DataTime parameter to stored procedure and check a condition - sql-server

assumption:
I need to sync a 'PublicDB' from a 'PrivateDB' database. Where two parameters should pass to stored procedure, server name and a datetime type parameter.
HistoryDate is not primary key but use for updating.
Scenario:
If today is 8th and user do not select any previous date from dateTimePicker -UI- this stored procedure only will update records on 8th.
If today is 8th and user select 5th of month= targetdate in my SP, it should delete 'PublicDB' table from 4th then insert 5th, 6th and 8th again.
Problem:
server parameter works fine but for datatime parameter:
If Sp execute in sql server get this error:
Conversion failed when converting date and/or time from character string.
if added to table Adapter it got this error:
Generated SELECT statement
Conversation failed when converting date / or time from character string.
*To apply these settings to your query click finish*
here is the sp:
CREATE PROCEDURE [dbo].[spname] #Server SYSNAME,
#TDate NVARCHAR(50) --have tested: DateTime
AS
BEGIN
DECLARE #SQL1 NVARCHAR(2000);
DECLARE #SQL2 NVARCHAR(2000);
DECLARE #LastRecordDate DATETIME;
DECLARE #Count INT;
DECLARE #TargetDate DATETIME;
SET #TargetDate = CONVERT(DATETIME, #TDate, 121);
SET #Count = CONVERT(INT, 'SELECT COUNT(*) FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >= [' + #TargetDate + '] ');
EXECUTE sp_executesql #Count;
IF #Count > 0 BEGIN
SET #SQL1 = 'DELETE FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >= [' + #TargetDate + ']
INSERT INTO [PublicDB].[dbo].[TableName]
SELECT TOP 5
[HistoryDate]
,[columnName1]
,[columnName2]
,[columnName3]
,[columnName4]
,[columnName5]
,[columnName6]
FROM PrivateDB.dbo.TableName
WHERE HistoryDate >= [' + #TargetDate + ']
';
EXECUTE sp_executesql #SQL1;
END
ELSE BEGIN
SET #LastRecordDate = CONVERT(DATETIME, 'SELECT TOP 1 HistoryDate FROM [PublicDB].[dbo].[TableName] ORDER BY HistoryDate DESC', 121);
-- has tested: cast('SELECT TOP 1 HistoryDate FROM [Public].[dbo].[TableName] ORDER BY HistoryDate DESC' as datetime)
EXECUTE sp_executesql #LastRecordDate;
SET #SQL2 = '
INSERT INTO [' + #Server + '].[PublicDB].[dbo].[TableName]
SELECT TOP 5
[HistoryDate]
,[columnName1]
,[columnName2]
,[columnName3]
,[columnName4]
,[columnName5]
,[columnName6]
FROM PrivateDB.dbo.TableName
WHERE HistoryDate > [' + #LastRecordDate + ']
';
EXECUTE sp_executesql #SQL2;
END
END

I think these lines could be the problem
SET #Count = CONVERT(INT, 'SELECT COUNT(*) FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >= [' + #TargetDate + '] ');
You are asking to convert a string / datetime to an int
I guess that you are trying to get a count from the select statement, one way would be something like the following (not tested!)
CREATE TABLE #t_count(no int)
DECLARE #sqlcount varchar(1000)
DECLARE #count int
SET #sqlcount = 'INSERT into #t_count SELECT COUNT(*)
FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >=''' + convert(varchar(30),#TargetDate,120) + ''''
EXEC( #sqlcount )
SELECT #count = no FROM #t_count
example sqlfiddle
EDIT
I see you updated your answer a little http://sqlfiddle.com/#!2/d41d8/14528
but if you read the answer above, you will see that it
creates a temp table
CREATE TABLE #t_count(no int)
builds an sql string to insert the count into the temp table
SET #sqlcount = 'INSERT into #t_count SELECT COUNT(*)
FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >=''' + convert(varchar(30),#TargetDate,120) + ''''
EXEC( #sqlcount )
gets the count value from the table
SELECT #count = no FROM #t_count
Your edit does not do this!
Also you are enclosing literal values in [] for some reason these need removed
good
where historydate = '2012-12-12 12:12'
bad
where historydate = [2012-12-12 12:12]

Related

Using a temporary table on SRSS report

I have a stored procedure which works without a problem at the sql server side. However, when I feed a SRSS report with this stored procedure, I am having an error such as; Invalid object name '##tempTable'.
Here is my stored procedure;
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
SET #QUERY = N'SELECT * INTO ##tempTable ' +
N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar,#StartDate,112),'''') + '''' + ',' + '''' + QUOTENAME(CONVERT(varchar,#EndDate,112) + '''','''') + ')';
EXEC sp_executesql #QUERY;
SET NOCOUNT ON;
SELECT * FROM ##tempTable
drop table ##tempTable
END
GO
How can I solve this issue? Thanks.
A Table referenced in a Dynamic statement can only be referenced inside that dynamic statement. Take this simple query:
EXEC sp_executesql N'SELECT 1 AS I INTO #temp;';
SELECT *
FROM #temp;
Notice the statement fails with:
Msg 208, Level 16, State 0, Line 3
Invalid object name '#temp'.
It seems, however, you don't need to temporary table, and this will work fine:
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
SET #QUERY = N'SELECT * ' +
N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar(8),#StartDate,112),'''') + '''' + ',' + '''' + QUOTENAME(CONVERT(varchar(8),#EndDate,112) + '''','''') + ')';
EXEC sp_executesql #QUERY;
END;
Try doing this
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
SET #QUERY = N'SELECT * INTO ##temp_global ' +
N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar,#StartDate,112),'''') '''' + ',' + '''' + QUOTENAME(CONVERT(varchar,#EndDate,112) + '''','''') + ')';
EXECUTE (#QUERY)
SELECT * FROM ##temp_global
DROP TABLE ##temp_global
END
I think I had this once and I had to create the temp table initially with the column names specified and then insert into it, so that your dataset would be able to pick up the column names. So something like this may work:
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
CREATE TABLE ##tempTable ([ColumnOne] VARCHAR(10), [ColumnTwo] DATETIME) --Add required columns here
SET #QUERY = N'SELECT * FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar,#StartDate,112),'''') + '''' + ',' + '''' + QUOTENAME(CONVERT(varchar,#EndDate,112) + '''','''') + ')';
INSERT INTO ##tempTable ([ColumnOne],[ColumnTwo])
EXEC (#QUERY);
SET NOCOUNT ON;
SELECT * FROM ##tempTable
DROP TABLE ##tempTable
END
GO

SQL Server Table Parameter without defining fields [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

Mssql procedure doesn't return records

I wrote simply procedure, that should return some data.
When I simply replace execute query and put SELECT 1 It is returning 1. But when i paste EXECUTE query, it is return nothing. What should I do?
ALTER PROCEDURE [dbo].[PTC_Repor]
#camp VARCHAR(50),
#StartTime DATETIME,
#EndTime DATETIME
AS
BEGIN
EXECUTE('
SELECT ID,NAME
FROM [hpsdb].[dbo]. [' + #camp + ']
WHERE IS_CLEAR = 0
AND SUCCESS_COUNT = 0
AND DATA_STATUS = 5
AND CALL_TIME > ''' + #StartTime + '''
AND CALL_TIME <= ''' + #EndTime + '''
')
END
GO
You could try using sp_executesql so that you can pass the datetime values across directly and not force them to become strings:
declare #Parms nvarchar(max)
set #Parms = '#StartTime datetime, #EndTime datetime'
declare #SQL nvarchar(max)
set #SQL = 'SELECT ID,NAME
FROM [hpsdb].[dbo]. [' + #camp + ']
WHERE IS_CLEAR = 0
AND SUCCESS_COUNT = 0
AND DATA_STATUS = 5
AND CALL_TIME > #StartTime
AND CALL_TIME <= #EndTime'
EXEC sp_executesql #SQL,#Prams,#StartTime,#EndTime

Insert script for a particular set of rows in SQL

I am using SQL Server 2008. I use to take the script of my data from SQL table using Tasks --> Generate Scripts option.
Here is my problem:
Let's say I have 21,000 records in Employee table. When I take the script of this table, it takes the insert script for all 21000 records. What is the solution if I want to take only the script of 18000 records from the table?
Is there any solution using SQL query or from the tasks wizard?
Thanks in advance...
Create a new View where you select your desired rows from your Employee table e.g. SELECT TOP 21000...
Then simply script that View instead of the Table.
In case the views are not an option for you I wrote the following code based on the Aaron Bertrand's answer here that will give the insert statement for a single record in the db.
CREATE PROCEDURE dbo.GenerateSingleInsert
#table NVARCHAR(511), -- expects schema.table notation
#pk_column SYSNAME, -- column that is primary key
#pk_value NVARCHAR(10) -- change data type accordingly
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cols NVARCHAR(MAX), #vals NVARCHAR(MAX),
#valOut NVARCHAR(MAX), #valSQL NVARCHAR(MAX);
SELECT #cols = N'', #vals = N'';
SELECT #cols = #cols + ',' + QUOTENAME(name),
#vals = #vals + ' + '','' + ' + 'ISNULL('+REPLICATE(CHAR(39),4)+'+RTRIM(' +
CASE WHEN system_type_id IN (40,41,42,43,58,61) -- dateteime and time stamp type
THEN
'CONVERT(CHAR(8), ' + QUOTENAME(name) + ', 112) + '' ''+ CONVERT(CHAR(14), ' + QUOTENAME(name) + ', 14)'
WHEN system_type_id IN (35) -- text type
THEN
'REPLACE(CAST(' + QUOTENAME(name) + 'as nvarchar(MAX)),'+REPLICATE(CHAR(39),4)+','+REPLICATE(CHAR(39),6)+')'
ELSE
'REPLACE(' + QUOTENAME(name) + ','+REPLICATE(CHAR(39),4)+','+REPLICATE(CHAR(39),6)+')'
END
+ ')+' + REPLICATE(CHAR(39),4) + ',''null'') + '
FROM sys.columns WHERE [object_id] = OBJECT_ID(#table)
AND system_type_id <> 189 -- can't insert rowversion
AND is_computed = 0; -- can't insert computed columns
SELECT #cols = STUFF(#cols, 1, 1, ''),
#vals = REPLICATE(CHAR(39),2) + STUFF(#vals, 1, 6, '') + REPLICATE(CHAR(39),2) ;
SELECT #valSQL = N'SELECT #valOut = ' + #vals + ' FROM ' + #table + ' WHERE '
+ QUOTENAME(#pk_column) + ' = ''' + RTRIM(#pk_value) + ''';';
EXEC sp_executesql #valSQL, N'#valOut NVARCHAR(MAX) OUTPUT', #valOut OUTPUT;
SELECT SQL = 'INSERT ' + #table + '(' + #cols + ') SELECT ' + #valOut;
END
I took the above code and wrapped it the following proc that will use the where clause you give it to select which insert statements to create
CREATE PROCEDURE dbo.GenerateInserts
#table NVARCHAR(511), -- expects schema.table notation
#pk_column SYSNAME, -- column that is primary key
#whereClause NVARCHAR(500) -- the where clause used to parse down the data
AS
BEGIN
declare #temp TABLE ( keyValue nvarchar(10), Pos int );
declare #result TABLE ( insertString nvarchar(MAX) );
declare #query NVARCHAR(MAX)
set #query =
'with qry as
(
SELECT ' + #pk_column + ' as KeyValue, ROW_NUMBER() over(ORDER BY ' + #pk_column + ') Pos
from ' + #table + '
' + #whereClause + '
)
select * from qry'
insert into #temp
exec sp_sqlexec #query
Declare #i int, #key nvarchar(10)
select #i = count(*) from #temp
WHILE #i > 0 BEGIN
select #key = KeyValue from #temp where Pos = #i
insert into #result
exec [dbo].[GenerateSingleInsert] #table, #pk_column, #key
set #i = #i - 1
END
select insertString from #result
END
Calling it could look like the following. You pass in the table name, the table primary key and the where clause and you should end up with your insert statements.
set #whereClause = 'where PrettyColorsId > 1000 and PrettyColorsID < 5000'
exec [dbo].GenerateInserts 'dbo.PrettyColors', 'PrettyColorsID', #whereClause
set #whereClause = 'where Color in (' + #SomeValues + ')'
exec [dbo].GenerateInserts 'dbo.PrettyColors', 'PrettyColorsID', #whereClause

How to create a UDF or View in another database that references the correct sys.objects table in the caller?

Using SQL Server 2008, I'd like to create a UDF that gives me the create date of an object. This is the code:
create function dbo.GetObjCreateDate(#objName sysname) returns datetime as
begin
declare #result datetime
select #result = create_date from sys.objects where name = #objname
return #result
end
go
I'd like to put this UDF in the master database or some other shared database so that it is accessible from anywhere, except that if I do that then the sys.objects reference pulls from the master database instead of the database that I'm initiating my query from. I know you can do this as the information_schema views sit in master and just wrap calls to local instances of sys.objects, so I'm hoping there's a simple way to do that with my UDF as well.
Try this:
CREATE FUNCTION dbo.GetObjCreateDate(#objName sysname, #dbName sysname)
RETURNS datetime AS
BEGIN
DECLARE #createDate datetime;
DECLARE #params nvarchar(50);
DECLARE #sql nvarchar(500);
SET #params = '#createDate datetime OUTPUT';
SELECT #sql = 'SELECT #createDate = create_date FROM ' + #dbName + '.sys.objects WHERE name = ''' + #objname + '''';
EXEC sp_executesql #sql, #params, #createDate = #createDate OUTPUT;
RETURN #createDate
END
;
Why not do this instead?
Create a stored procedure that creates a view in the master database containing all of the information in sys.objects from each database on the server.
Create a DDL Trigger that gets fired whenever a CREATE, ALTER or DROP statement is executed for a database. The trigger would then execute the stored procedure in step #1. This allows the view to be automatically updated.
(Optional) Create a user defined function that queries the view for the creation date of a given object.
Stored Procedure DDL:
USE [master];
GO
CREATE PROCEDURE dbo.BuildAllServerObjectsView
AS
SET NOCOUNT ON;
IF OBJECT_ID('master.dbo.AllServerObjects') IS NOT NULL
EXEC master..sp_SQLExec 'DROP VIEW dbo.AllServerObjects;';
IF OBJECT_ID('tempdb..Databases') IS NOT NULL
DROP TABLE #Databases;
DECLARE #CreateView varchar(8000);
SET #CreateView = 'CREATE VIEW dbo.AllServerObjects AS' + CHAR(13)+CHAR(10) + CHAR(13)+CHAR(10);
SELECT name COLLATE SQL_Latin1_General_CP1_CI_AS AS 'name'
INTO #Databases
FROM sys.databases
ORDER BY name;
DECLARE #DatabaseName nvarchar(100);
WHILE (SELECT COUNT(*) FROM #Databases) > 0
BEGIN
SET #DatabaseName = (SELECT TOP 1 name FROM #Databases ORDER BY name);
SET #CreateView +='SELECT N'+QUOTENAME(#DatabaseName, '''')+' AS ''database_name''' + CHAR(13)+CHAR(10)
+ ' ,name COLLATE SQL_Latin1_General_CP1_CI_AS AS ''object_name''' + CHAR(13)+CHAR(10)
+ ' ,object_id' + CHAR(13)+CHAR(10)
+ ' ,principal_id' + CHAR(13)+CHAR(10)
+ ' ,schema_id' + CHAR(13)+CHAR(10)
+ ' ,parent_object_id' + CHAR(13)+CHAR(10)
+ ' ,type' + CHAR(13)+CHAR(10)
+ ' ,type_desc' + CHAR(13)+CHAR(10)
+ ' ,create_date' + CHAR(13)+CHAR(10)
+ ' ,modify_date' + CHAR(13)+CHAR(10)
+ ' ,is_ms_shipped' + CHAR(13)+CHAR(10)
+ ' ,is_published' + CHAR(13)+CHAR(10)
+ ' ,is_schema_published' + CHAR(13)+CHAR(10)
+ ' FROM ' + QUOTENAME(#DatabaseName) + '.sys.objects';
IF (SELECT COUNT(*) FROM #Databases) > 1
SET #CreateView += CHAR(13)+CHAR(10) + CHAR(13)+CHAR(10) + ' UNION' + CHAR(13)+CHAR(10);
ELSE
SET #CreateView += ';';
DELETE #Databases
WHERE name = #DatabaseName;
END;
--PRINT #CreateView --<== Uncomment this to see the DDL for the view.
EXEC master..sp_SQLExec #CreateView;
IF OBJECT_ID('tempdb..Databases') IS NOT NULL
DROP TABLE #Databases;
GO
Function DDL:
USE [master];
GO
CREATE FUNCTION dbo.GetObjCreateDate(#DatabaseName sysname, #objName sysname) RETURNS DATETIME AS
BEGIN
DECLARE #result datetime;
SELECT #result = create_date
FROM master.dbo.AllServerObjects
WHERE [database_name] = #DatabaseName
AND [object_name] = #objname;
RETURN #result;
END
GO
Sample Usage:
SELECT master.dbo.GetObjCreateDate('MyDatabase', 'SomeObject') AS 'Created';
SELECT master.dbo.GetObjCreateDate(DB_NAME(), 'spt_monitor') AS 'Created';
Does it have to be a function? If you just want it accessible everywhere, a trick is to put your code in a varchar and sp_executesql it:
create procedure dbo.GetObjCreateDate(#objName sysname)
as
declare #sql nvarchar(max)
select #sql = 'select create_date from sys.objects where name = ''' + #objname + ''''
EXEC sp_executesql #sql
go
There seems to be an undocumented stored procedure that allows you to create your own system objects: sp_ms_marksystemobject
You can read more on http://www.mssqltips.com/tip.asp?tip=1612
Have a look at How to Write Your Own System Functions. I believe that it may help you

Resources