Showing posts with label store. Show all posts
Showing posts with label store. Show all posts

Thursday, March 29, 2012

get a return value from an insert without using a stored proc.

hi all,

lets say i have this insert command being executed from C# to a SQL Db.

//store transaction logSqlCommand cmdStoreTrans =new SqlCommand("INSERT into Transactions(ImportID,ProfileID,RowID) values (@.ImportID,@.ProfileID,@.RowID);",conn);cmdStoreTrans.Parameters.Add("@.ImportID",importId);cmdStoreTrans.Parameters.Add("@.ProfileID",profileId);cmdStoreTrans.Parameters.Add("@.RowID",i);try{conn.Open();cmdStoreTrans.ExecuteNonQuery();conn.Close();}catch(SqlException ex){throw(ex);}

I need the new Identity number of that record added. how can i get that within THIS Sqlcommand. Currently im closing the connection, creating a new command with 'SELECT MAX(id) from transactions" and getting the value that way, im sure there is a easier way keeping it all within one command object? someone mentioned using something liek @.@.Identity

any help appreciated

TIA, mcm

Try doing a SELECT SCOPE_IDENTITY() at the end of your INSERT statement. and use ExecuteScalar instead of ExecuteNonQuery.|||

thanks,

will do.

mcm

Tuesday, March 27, 2012

Geographical data in SQL Server

Hi,
Is there any way to use SQL server to store and query geographical data? For
example, be able to query all the records that fall withing certain
geographical poligon defined by lat/lon coordinates?
Thanks.
You're talking about GIS. You could store the data in SQL but you're
probably going to use MapInfo or ArcInfo to perform the geographical
queries..
Tim Heap
Software & Database Manager
POSTAR Ltd
www.postar.co.uk
tim@.postar.co.uk
*** Sent via Developersdex http://www.codecomments.com ***

Geographical data in SQL Server

Hi,
Is there any way to use SQL server to store and query geographical data? For
example, be able to query all the records that fall withing certain
geographical poligon defined by lat/lon coordinates?
Thanks.You're talking about GIS. You could store the data in SQL but you're
probably going to use MapInfo or ArcInfo to perform the geographical
queries..
Tim Heap
Software & Database Manager
POSTAR Ltd
www.postar.co.uk
tim@.postar.co.uk
*** Sent via Developersdex http://www.codecomments.com ***

Geographic Locations in a database

Hi

Has anyone ever tried to store international address information in to a single data

example

UK Address
Nildram Ltd
Ardenham Court
Oxford Road
AYLESBURY
BUCKINGHAMSHIRE
HP19 3EQ
GREAT BRITAIN

US Address
CHRIS NISWANDEE
BITBOOST SYSTEMS
421 E DRACHMAN
TUCSON AZ 85705
USA

Spainish Address
Organismo Autnomio Correos y Telgraphos
Area de Asuntos Internacionales
Calle Aduana, 29
28070 MADRID
SPAIN

Has anyone ever normalised this information into a database, because Im not sure if I should create separate tables or US States etc. Are there any other countries that contain data such as states?

Im just wondering how large organisation such as Yahoo or Microsoft would store this information.

Regards
Bennettas you have posted a question in the articles section it is being moved to SQL Server Forum.

MODERATOR.

Friday, March 23, 2012

Generating SQL Script

Hello there
I have huge database on sql server. The database probide tables, views,
store procedures and functions
Some of the views or the store procedures are depend on the functions, store
presedures are depend on the views.
When i update the version I generate SQL Script and run it on my client
The script first of all destroy objects on the client and establish the new
schema. The sql script firs create tables, views, store procedures and at
finaly functions.
Because some of the views or the store procedures are using the functions
they can't be created.
What i need to do to create first the functions?
and if on the future i will create functions that using functions. Is there
a "smart" script that first of all create the objects without any
dependencies and after that create wnat under them?
any help would be usefulI have the same problem with some scripts I generate. Here's the solutions
I came up with:
1) manually re-arrange the script so that objects that need to be created
first are created first, or
2) generate multiple scripts (generate one that just creates functions, one
that just creates views, etc.)
I prefer the second method myself, since it's less work, especially for very
large scripts.
Thx
"Roy Goldhammer" <roygoldh@.hotmail.com> wrote in message
news:%23blV03ZHFHA.400@.TK2MSFTNGP14.phx.gbl...
> Hello there
> I have huge database on sql server. The database probide tables, views,
> store procedures and functions
> Some of the views or the store procedures are depend on the functions,
> store
> presedures are depend on the views.
> When i update the version I generate SQL Script and run it on my client
> The script first of all destroy objects on the client and establish the
> new
> schema. The sql script firs create tables, views, store procedures and at
> finaly functions.
> Because some of the views or the store procedures are using the functions
> they can't be created.
> What i need to do to create first the functions?
> and if on the future i will create functions that using functions. Is
> there
> a "smart" script that first of all create the objects without any
> dependencies and after that create wnat under them?
> any help would be useful
>

Monday, March 19, 2012

Generating hash value

Following Microsoft recommendations, I'd like to store a one-way passport
hash of a user's password. .NET provides method
FormsAuthentication.HashPasswordForStoringinConfigFile (...) to generate a
hash value with either SHA1 or MD5 algorithm. My problem is that the
password is to be generated on a workstation with no .NET installed. How can
I generate a hash value without .NET in the same way as
HashPasswordForStoringinConfigFile does? Is there any sequence of Windows
Crypto API calls with the same effect? An external stored procedure on the
server side?
EliyahuYes, CryptoAPI supports calculating hashes using functions:
CryptCreateHash
CryptHashData
CryptGetHashParam (with dwParam = HP_HASHVAL to get actual hash buffer)
Start here:
http://msdn.microsoft.com/library/d...data_hashes.asp
The byte order in the capi buffer returned is identical to data in .NET
HashPasswordForStoringinConfigFile string.
You only need to convert the byte buffer into an ordered hex-string to match
the .NET hash string.
- Michel Gallant
MVP Security
"Eliyahu Goldin" <removemeegoldin@.monarchmed.com> wrote in message
news:Orw0CVVzDHA.2932@.TK2MSFTNGP09.phx.gbl...
quote:

> Following Microsoft recommendations, I'd like to store a one-way passport
> hash of a user's password. .NET provides method
> FormsAuthentication.HashPasswordForStoringinConfigFile (...) to generate a
> hash value with either SHA1 or MD5 algorithm. My problem is that the
> password is to be generated on a workstation with no .NET installed. How c
an
> I generate a hash value without .NET in the same way as
> HashPasswordForStoringinConfigFile does? Is there any sequence of Windows
> Crypto API calls with the same effect? An external stored procedure on the
> server side?
> Eliyahu
>
|||> Crypto API calls with the same effect? An external stored procedure on the
quote:

> server side?

you can use XP_CRYPT (www.activecrypt.com). Free version supports SHA1, MD5
and DES hashes without limitations.|||Thanks Michel and Andy,
Your answers are exactly what I need.
Eliyahu

Friday, March 9, 2012

Generate Store Procedure ?

I have a table in database !
I want to generate store procedure from that table by using tool of SQL server 2000( which include some statements : insert,delete, ....)
how can i do that ? thank you very much .

Try the link below and test drive the tool it was created by the best T-SQL programmers before the BMC bought them. Hope this helps.

http://www.bmc.com/products/proddocview/0,,0_0_0_8739,00.html

Sunday, February 26, 2012

Generate Script - Specified cast is not valid

When trying to generate a script, from SQL Server Management Studio, for the
following Store Procedure ( SP ) I receive the following error. I have
dropped and recreated the Store Procedure but I continue to get the error.
CREATE PROCEDURE dbo.usp_CreditCardSaveTargetQueue_S_Count
@.RecordCount INT OUTPUT
AS
SET NOCOUNT ON
SELECT @.RecordCount = COUNT(*)
FROM CreditCardSaveTargetQueue
WITH(NOLOCK) WHERE validation = 'X'
GO
-- **************************************************************
Error:
TITLE: Microsoft.SqlServer.SqlEnum
--
Failed to retrieve dependency information (object_id(System.Int32)
1952726009.object_type(System.Int16) 4.relative_id(System.Int32)
731149650.relative_type(System.DBNull) .object_name(System.String)
usp_CreditCardSaveTargetQueue_S_Count.object_schema(System.String)
dbo.relative_name(System.DBNull) .relative_schema(System.DBNull) .).
--
ADDITIONAL INFORMATION:
Specified cast is not valid. (Microsoft.SqlServer.SqlEnum)I'm having the same problem and have tried the same resolution
(dropping/recreating stored procedure). If I try to script the database and
include this stored procedure, it fails. If I try to view dependencies to
this stored procedure it fails. Specified cast is not valid.
(Microsoft.SqlServer.SqlEnum).
"BarDev" wrote:
> When trying to generate a script, from SQL Server Management Studio, for the
> following Store Procedure ( SP ) I receive the following error. I have
> dropped and recreated the Store Procedure but I continue to get the error.
>
> CREATE PROCEDURE dbo.usp_CreditCardSaveTargetQueue_S_Count
> @.RecordCount INT OUTPUT
> AS
> SET NOCOUNT ON
> SELECT @.RecordCount = COUNT(*)
> FROM CreditCardSaveTargetQueue
> WITH(NOLOCK) WHERE validation = 'X'
> GO
> -- **************************************************************
> Error:
> TITLE: Microsoft.SqlServer.SqlEnum
> --
> Failed to retrieve dependency information (object_id(System.Int32)
> 1952726009.object_type(System.Int16) 4.relative_id(System.Int32)
> 731149650.relative_type(System.DBNull) .object_name(System.String)
> usp_CreditCardSaveTargetQueue_S_Count.object_schema(System.String)
> dbo.relative_name(System.DBNull) .relative_schema(System.DBNull) .).
> --
> ADDITIONAL INFORMATION:
> Specified cast is not valid. (Microsoft.SqlServer.SqlEnum)
>

Generate Script - Specified cast is not valid

When trying to generate a script, from SQL Server Management Studio, for the
following Store Procedure ( SP ) I receive the following error. I have
dropped and recreated the Store Procedure but I continue to get the error.
CREATE PROCEDURE dbo.usp_CreditCardSaveTargetQueue_S_Count
@.RecordCount INT OUTPUT
AS
SET NOCOUNT ON
SELECT @.RecordCount = COUNT(*)
FROM CreditCardSaveTargetQueue
WITH(NOLOCK) WHERE validation = 'X'
GO
-- ****************************************
**********************
Error:
TITLE: Microsoft.SqlServer.SqlEnum
--
Failed to retrieve dependency information (object_id(System.Int32)
1952726009.object_type(System.Int16) 4.relative_id(System.Int32)
731149650.relative_type(System.DBNull) .object_name(System.String)
usp_CreditCardSaveTargetQueue_S_Count.object_schema(System.String)
dbo.relative_name(System.DBNull) .relative_schema(System.DBNull) .).
ADDITIONAL INFORMATION:
Specified cast is not valid. (Microsoft.SqlServer.SqlEnum)I'm having the same problem and have tried the same resolution
(dropping/recreating stored procedure). If I try to script the database and
include this stored procedure, it fails. If I try to view dependencies to
this stored procedure it fails. Specified cast is not valid.
(Microsoft.SqlServer.SqlEnum).
"BarDev" wrote:

> When trying to generate a script, from SQL Server Management Studio, for t
he
> following Store Procedure ( SP ) I receive the following error. I have
> dropped and recreated the Store Procedure but I continue to get the error.
>
> CREATE PROCEDURE dbo.usp_CreditCardSaveTargetQueue_S_Count
> @.RecordCount INT OUTPUT
> AS
> SET NOCOUNT ON
> SELECT @.RecordCount = COUNT(*)
> FROM CreditCardSaveTargetQueue
> WITH(NOLOCK) WHERE validation = 'X'
> GO
> -- ****************************************
**********************
> Error:
> TITLE: Microsoft.SqlServer.SqlEnum
> --
> Failed to retrieve dependency information (object_id(System.Int32)
> 1952726009.object_type(System.Int16) 4.relative_id(System.Int32)
> 731149650.relative_type(System.DBNull) .object_name(System.String)
> usp_CreditCardSaveTargetQueue_S_Count.object_schema(System.String)
> dbo.relative_name(System.DBNull) .relative_schema(System.DBNull) .).
> --
> ADDITIONAL INFORMATION:
> Specified cast is not valid. (Microsoft.SqlServer.SqlEnum)
>|||I'm having the same problem and have tried the same resolution
(dropping/recreating stored procedure). If I try to script the database and
include this stored procedure, it fails. If I try to view dependencies to
this stored procedure it fails. Specified cast is not valid.
(Microsoft.SqlServer.SqlEnum).
"BarDev" wrote:

> When trying to generate a script, from SQL Server Management Studio, for t
he
> following Store Procedure ( SP ) I receive the following error. I have
> dropped and recreated the Store Procedure but I continue to get the error.
>
> CREATE PROCEDURE dbo.usp_CreditCardSaveTargetQueue_S_Count
> @.RecordCount INT OUTPUT
> AS
> SET NOCOUNT ON
> SELECT @.RecordCount = COUNT(*)
> FROM CreditCardSaveTargetQueue
> WITH(NOLOCK) WHERE validation = 'X'
> GO
> -- ****************************************
**********************
> Error:
> TITLE: Microsoft.SqlServer.SqlEnum
> --
> Failed to retrieve dependency information (object_id(System.Int32)
> 1952726009.object_type(System.Int16) 4.relative_id(System.Int32)
> 731149650.relative_type(System.DBNull) .object_name(System.String)
> usp_CreditCardSaveTargetQueue_S_Count.object_schema(System.String)
> dbo.relative_name(System.DBNull) .relative_schema(System.DBNull) .).
> --
> ADDITIONAL INFORMATION:
> Specified cast is not valid. (Microsoft.SqlServer.SqlEnum)
>

Sunday, February 19, 2012

Generate Alter Script

Hi,

I read some related threads but none seem to answer my question. How to script a udf or a store procedure that exists in my database as an ALTER script. I don't want to modify the udf to be able to capture it(captureSql). I just want to script it as an ALTER. The scriptingOptions contains the DROP but I did not see the ALTER. I know SSMS does that when I right click on a store procedure I have the option to script it as ALTER.

I am guessing I can get the script then replace the CREATE with ALTER but that does not look to me a good solution. I am hoping there is something in SMO I can use.

Thanks,
Elie

Source Code Sample:

Code Block

using System;

using System.Configuration;

using System.Collections.Generic;

using System.Text;

using Microsoft.SqlServer.Management.Common;

using Microsoft.SqlServer.Management.Smo;

using System.Threading;

using System.Collections.Specialized;

using System.IO;

using System.Text.RegularExpressions;

namespace SMOEvents

{

class SmoEvents

{

private static Server server = null;

private static Database db = null;

private static string folderPath = "";

private static string procedureNamePattern = "";

private static string fileNameExnention = "";

static void Main(string[] args)

{

#region config data

string connString = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).ConnectionStrings.ConnectionStrings["MSSqlServer"].ToString();

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connString);

if (!builder.IntegratedSecurity)

{

SqlConnectionInfo ci = new SqlConnectionInfo(builder.DataSource, builder.UserID, builder.Password);

ServerConnection serverConn = new ServerConnection(ci);

server = new Server(serverConn);

}

else

{

server = new Server(builder.DataSource);

}

if (builder.InitialCatalog != "")

{

db = server.Databases[builder.InitialCatalog];

}

else {

db = server.Databases[0];

}

procedureNamePattern = ConfigurationManager.AppSettings.GetValues("ProcedureNamePattern").GetValue(0).ToString();

folderPath = ConfigurationManager.AppSettings.GetValues("LocalFolderPath").GetValue(0).ToString();

fileNameExnention = ConfigurationManager.AppSettings.GetValues("FileNameExnention").GetValue(0).ToString();

#endregion

if (args.Length > 0)

{

if (args[0].ToString() == "ListenEvents")

{

ListenEvents();

}

else

{

ScriptAllProcedures();

return;

}

}

else {

ScriptAllProcedures();

return;

}

}

private static void ScriptAllProcedures()

{

Regex rx = new Regex(procedureNamePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

foreach (StoredProcedure sp in db.StoredProcedures)

{

if ((!sp.IsEncrypted) && (!sp.IsSystemObject) && (rx.IsMatch(sp.Name)))

{

string fileName = folderPath + sp.Schema + "." + sp.Name + fileNameExnention;

ScriptProcedure(sp, fileName);

}

}

}

private static void ScriptProcedure(StoredProcedure sp, string fileName)

{

FileInfo fi = new FileInfo(fileName);

if ((!fi.Exists) ||(fi.Exists && !fi.IsReadOnly))

{

string body = "IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + sp.Schema + "].[" + sp.Name + "]') AND type in (N'P', N'PC'))";

body = body + "\r\n" + " DROP PROCEDURE [" + sp.Schema + "].[" + sp.Name + "]";

body = body + "\r\n" + "GO\n";

body = body + "\r\n" + "SET ANSI_NULLS ON";

body = body + "\r\n" + "GO";

body = body + "\r\n" + "SET QUOTED_IDENTIFIER ON";

body = body + "\r\n" + "GO";

body = body + "\r\n";

body = body + "\r\n" + sp.TextHeader;

body = body + "\r\n" + sp.TextBody;

body = body + "\r\n" + "GO";

body = body + "\r\n";

body = body + "\r\n" + "SET ANSI_NULLS OFF";

body = body + "\r\n" + "GO";

body = body + "\r\n" + "SET QUOTED_IDENTIFIER OFF";

body = body + "\r\n" + "GO";

File.WriteAllText(fileName, body, UnicodeEncoding.Unicode);

Console.WriteLine(@."{0} ", fileName);

}

}

private static void ListenEvents()

{

db.Events.ServerEvent += new ServerEventHandler(Events_ServerEvent);

// DDL events

db.Events.SubscribeToEvents(DatabaseEvent.AlterProcedure + DatabaseEvent.CreateProcedure);

Console.WriteLine(@."Starting events for server: {0}", server.Name);

Console.WriteLine();

Console.WriteLine(@."(Hit Ctrl-C or Ctrl-Break to quit.)");

//Console.WriteLine(@."Press any key to continue.");

//Console.ReadKey();

Console.WriteLine(@."Start listening: {0}", DateTime.Now);

// Start receiving events

db.Events.StartEvents();

// Wait indefinitely for events to occur

Thread.Sleep(Timeout.Infinite);

Console.WriteLine(@."Stop listening ...");

// Unsubscribe from all the events when finished

server.Events.UnsubscribeAllEvents();

}

/// <summary>

/// to avoid Access Denied Error you should execute the following script:

/// ALTER DATABASE [@.dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

/// go

/// ALTER DATABASE [@.dbname] SET ENABLE_BROKER

/// go

/// ALTER DATABASE [@.dbname] SET MULTI_USER

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

static void Events_ServerEvent(object sender, ServerEventArgs e)

{

try

{

if (e.Properties["ObjectName"] != null)

{

StoredProcedure sp = db.StoredProcedures[e.Properties["ObjectName"].Value.ToString()];

if ((!sp.IsEncrypted) && (!sp.IsSystemObject))

{

string fileName = folderPath + sp.Schema + "." + sp.Name + fileNameExnention;

ScriptProcedure(sp, fileName);

}

}

Console.WriteLine(@."EventType: {0, -20} SPID: {1, 4} PostTime: {2, -20}", e.EventType, e.Spid, e.PostTime);

Console.WriteLine();

}

catch (ApplicationException ex)

{

Console.WriteLine(ex.ToString());

}

}

}

}

App.Config Sample:

Code Block

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="ProcedureNamePattern" value=".+"/>

<add key="FileNameExnention" value=".sql"/>

<add key="LocalFolderPath" value=".\Stored Procedures\"/>

</appSettings>

<connectionStrings>

<add name="MSSqlServer" connectionString="Data Source=.;Integrated Security=true;Initial Catalog=AdventureWorks;" providerName="System.Data.SqlClient" />

</connectionStrings>

</configuration>

|||

Thanks for the code.

I tried the code with the Listenevents option but I am getting an error: ProviderLoadFailure

on this line db.Events.StartEvents();

The ScriptProcedure() does script it as create. But I am looking for a way to be scripted as Alter.

Thanks

Elie

|||

Scripting with CREATE and replacing the CREATE with ALTER I believe is the only way you can get it done with SMO. There is not a native ALTER creation in SMO (that is documented).

|||

Thanks I thought so. I wish I found the documentation.

Elie

Generate Alter Script

Hi,

I read some related threads but none seem to answer my question. How to script a udf or a store procedure that exists in my database as an ALTER script. I don't want to modify the udf to be able to capture it(captureSql). I just want to script it as an ALTER. The scriptingOptions contains the DROP but I did not see the ALTER. I know SSMS does that when I right click on a store procedure I have the option to script it as ALTER.

I am guessing I can get the script then replace the CREATE with ALTER but that does not look to me a good solution. I am hoping there is something in SMO I can use.

Thanks,
Elie

Source Code Sample:

Code Block

using System;

using System.Configuration;

using System.Collections.Generic;

using System.Text;

using Microsoft.SqlServer.Management.Common;

using Microsoft.SqlServer.Management.Smo;

using System.Threading;

using System.Collections.Specialized;

using System.IO;

using System.Text.RegularExpressions;

namespace SMOEvents

{

class SmoEvents

{

private static Server server = null;

private static Database db = null;

private static string folderPath = "";

private static string procedureNamePattern = "";

private static string fileNameExnention = "";

static void Main(string[] args)

{

#region config data

string connString = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).ConnectionStrings.ConnectionStrings["MSSqlServer"].ToString();

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connString);

if (!builder.IntegratedSecurity)

{

SqlConnectionInfo ci = new SqlConnectionInfo(builder.DataSource, builder.UserID, builder.Password);

ServerConnection serverConn = new ServerConnection(ci);

server = new Server(serverConn);

}

else

{

server = new Server(builder.DataSource);

}

if (builder.InitialCatalog != "")

{

db = server.Databases[builder.InitialCatalog];

}

else {

db = server.Databases[0];

}

procedureNamePattern = ConfigurationManager.AppSettings.GetValues("ProcedureNamePattern").GetValue(0).ToString();

folderPath = ConfigurationManager.AppSettings.GetValues("LocalFolderPath").GetValue(0).ToString();

fileNameExnention = ConfigurationManager.AppSettings.GetValues("FileNameExnention").GetValue(0).ToString();

#endregion

if (args.Length > 0)

{

if (args[0].ToString() == "ListenEvents")

{

ListenEvents();

}

else

{

ScriptAllProcedures();

return;

}

}

else {

ScriptAllProcedures();

return;

}

}

private static void ScriptAllProcedures()

{

Regex rx = new Regex(procedureNamePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

foreach (StoredProcedure sp in db.StoredProcedures)

{

if ((!sp.IsEncrypted) && (!sp.IsSystemObject) && (rx.IsMatch(sp.Name)))

{

string fileName = folderPath + sp.Schema + "." + sp.Name + fileNameExnention;

ScriptProcedure(sp, fileName);

}

}

}

private static void ScriptProcedure(StoredProcedure sp, string fileName)

{

FileInfo fi = new FileInfo(fileName);

if ((!fi.Exists) ||(fi.Exists && !fi.IsReadOnly))

{

string body = "IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + sp.Schema + "].[" + sp.Name + "]') AND type in (N'P', N'PC'))";

body = body + "\r\n" + " DROP PROCEDURE [" + sp.Schema + "].[" + sp.Name + "]";

body = body + "\r\n" + "GO\n";

body = body + "\r\n" + "SET ANSI_NULLS ON";

body = body + "\r\n" + "GO";

body = body + "\r\n" + "SET QUOTED_IDENTIFIER ON";

body = body + "\r\n" + "GO";

body = body + "\r\n";

body = body + "\r\n" + sp.TextHeader;

body = body + "\r\n" + sp.TextBody;

body = body + "\r\n" + "GO";

body = body + "\r\n";

body = body + "\r\n" + "SET ANSI_NULLS OFF";

body = body + "\r\n" + "GO";

body = body + "\r\n" + "SET QUOTED_IDENTIFIER OFF";

body = body + "\r\n" + "GO";

File.WriteAllText(fileName, body, UnicodeEncoding.Unicode);

Console.WriteLine(@."{0} ", fileName);

}

}

private static void ListenEvents()

{

db.Events.ServerEvent += new ServerEventHandler(Events_ServerEvent);

// DDL events

db.Events.SubscribeToEvents(DatabaseEvent.AlterProcedure + DatabaseEvent.CreateProcedure);

Console.WriteLine(@."Starting events for server: {0}", server.Name);

Console.WriteLine();

Console.WriteLine(@."(Hit Ctrl-C or Ctrl-Break to quit.)");

//Console.WriteLine(@."Press any key to continue.");

//Console.ReadKey();

Console.WriteLine(@."Start listening: {0}", DateTime.Now);

// Start receiving events

db.Events.StartEvents();

// Wait indefinitely for events to occur

Thread.Sleep(Timeout.Infinite);

Console.WriteLine(@."Stop listening ...");

// Unsubscribe from all the events when finished

server.Events.UnsubscribeAllEvents();

}

/// <summary>

/// to avoid Access Denied Error you should execute the following script:

/// ALTER DATABASE [@.dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

/// go

/// ALTER DATABASE [@.dbname] SET ENABLE_BROKER

/// go

/// ALTER DATABASE [@.dbname] SET MULTI_USER

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

static void Events_ServerEvent(object sender, ServerEventArgs e)

{

try

{

if (e.Properties["ObjectName"] != null)

{

StoredProcedure sp = db.StoredProcedures[e.Properties["ObjectName"].Value.ToString()];

if ((!sp.IsEncrypted) && (!sp.IsSystemObject))

{

string fileName = folderPath + sp.Schema + "." + sp.Name + fileNameExnention;

ScriptProcedure(sp, fileName);

}

}

Console.WriteLine(@."EventType: {0, -20} SPID: {1, 4} PostTime: {2, -20}", e.EventType, e.Spid, e.PostTime);

Console.WriteLine();

}

catch (ApplicationException ex)

{

Console.WriteLine(ex.ToString());

}

}

}

}

App.Config Sample:

Code Block

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="ProcedureNamePattern" value=".+"/>

<add key="FileNameExnention" value=".sql"/>

<add key="LocalFolderPath" value=".\Stored Procedures\"/>

</appSettings>

<connectionStrings>

<add name="MSSqlServer" connectionString="Data Source=.;Integrated Security=true;Initial Catalog=AdventureWorks;" providerName="System.Data.SqlClient" />

</connectionStrings>

</configuration>

|||

Thanks for the code.

I tried the code with the Listenevents option but I am getting an error: ProviderLoadFailure

on this line db.Events.StartEvents();

The ScriptProcedure() does script it as create. But I am looking for a way to be scripted as Alter.

Thanks

Elie

|||

Scripting with CREATE and replacing the CREATE with ALTER I believe is the only way you can get it done with SMO. There is not a native ALTER creation in SMO (that is documented).

|||

Thanks I thought so. I wish I found the documentation.

Elie

generate a email using smtp server (was "Help with query....")

Help with query: I currently cannot be alerted by SQL Mail so I would like to take the script that was generated by SQL server and using the store procedure sp_sqlsmtpmail to generate a email using smtp server to alert me. The store procedure does work. I would like to know if this is possible.

Thanks

Lystra

-- Script generated on 1/21/2005 10:04 AM
-- By: MAMSI\sa
-- Server: (local)

IF (EXISTS (SELECT name FROM msdb.dbo.sysalerts WHERE name = N'Demo: Full tempdb'))
-- Delete the alert with the same name.
EXECUTE msdb.dbo.sp_delete_alert @.name = N'Demo: Full tempdb'
BEGIN
EXECUTE msdb.dbo.sp_add_alert @.name = N'Demo: Full tempdb', @.message_id = 9002, @.severity = 0, @.enabled = 1, @.delay_between_responses = 10, @.include_event_description_in = 5, @.database_name = N'tempdb', @.category_name = N'[Uncategorized]'

Then

Exec sp_sqlsmtpmail
@.vcTo = 'lwilliams@.Huc.com',
@.vcBody ='Check out problem Immediataly.',
@.vcSubject ='DOCSITE01FDK - Full Tempdb Log'

ENDYou can have the alert execute a job that has the call to sp_sqlsmtpmail in one of it's steps.|||Great idea, thanks.

Lystra