In many situations, I just want to grab one or two rows from a table and script out the inserts. It would be nice if SMO did this for me automatically, including handling whether to generate "set identity_insert [schema].[table_name] on/off" lines.I can't use the traditional way to dump table data:ScriptingOptions.ScriptData = trueThis option scripts out EVERYTHING. I just want one row, e.g. the row where a PK equals 0.What's the best way to do this?
↧
SMO Transfering specific rows from specific tables?
↧
Powershell for data transfer from non-SQL Server database
I have a tool that uses SSIS and stored procedures to extract data from a non-SQL Server database (Sybase) and loads the data into a SQL Server database. I have upgraded to SQL Server 2008 R2 and I am in the process of upgrading to Powershell 2.0. I want to wrap this process in a Powershell script and I would like to be able to remove SSIS from the equation if there is an OLEDB type SMO object available which would allow me to connect to a Sybase database source and manage the data in much the same way as I manage SQL Server databases through the use of SMO.
↧
↧
Microsoft.SqlServer.Management.Smo.DatabaseStatus values different from sysdatabases status column values
Not sure if anyone noticed this. Looks like the status bits defined in SMO object is not actually same as that stored in status column of sysdatabases. As I am using SMO i am not able to exactly figure out the status of the database when status goes to offline. I know that I can use DATABASEPROPERTYEX which gives the status in string but I would like to get the status bit value.KiranStatus bits defined in sysdatabasesstatus int Status bits, some of which can be set by using ALTER DATABASE as noted:1 = autoclose (ALTER DATABASE)4 = select into/bulkcopy (ALTER DATABASE using SET RECOVERY) 8 = trunc. log on chkpt (ALTER DATABASE using SET RECOVERY) 16 = torn page detection (ALTER DATABASE) 32 = loading 64 = pre recovery 128 = recovering 256 = not recovered 512 = offline (ALTER DATABASE) 1024 = read only (ALTER DATABASE) 2048 = dbo use only (ALTER DATABASE using SET RESTRICTED_USER) 4096 = single user (ALTER DATABASE) 32768 = emergency mode4194304 = autoshrink (ALTER DATABASE)1073741824 = cleanly shutdownMultiple bits can be ON at the same time Status bit defined in SMO.namespace Microsoft.SqlServer.Management.Smo{ // Summary: // The Microsoft.SqlServer.Management.Smo.DatabaseStatus enumeration is a list // of constant values that specify the status of a database, whether it be loading, // recovering, or normal, for example. This enumeration has a FlagsAttribute // attribute that allows a bitwise combination of its member values. [Flags] public enum DatabaseStatus { // Summary: // The database is available. Normal = 1, // // Summary: // The database is going through the restore process. Restoring = 2, // // Summary: // The database is waiting to go through the recovery process. RecoveryPending = 4, // // Summary: // The database is going through the recovery process. Recovering = 8, // // Summary: // The database has been marked as suspect. You will have to check the data, // and the database might have to be restored from a backup. Suspect = 16, // // Summary: // The database has been taken offline. Offline = 32, // // Summary: // The database is inaccessible. The server might be switched off or the network // connection has been interrupted. Inaccessible = 62, // // Summary: // The database is in standby mode. Standby = 64, // // Summary: // The server on which the database resides has been shut down. Shutdown = 128, // // Summary: // The database is in emergency mode. EmergencyMode = 256, // // Summary: // The database has been automatically closed. AutoClosed = 512, }}
↧
How to retrieve the table names from a View using SMO
Hi,I am writing a User Interface to view all the SMO.View objects and display the components involved in it. One of the issues I am having is to retrieve all the tables involved in an existing View. I can see all the columns involved. But the Column.Parent only points to the View itself. I need the names of the tables for each column including their alias if any. I can see this information in the View.TextBody. I can also see the column information by calling View.EnumColumns(). But I can't find the table information anywhere. I am sure this information is stored somewhere in the view or elsewhere on the database. Can someone help me with this please? I really appreciate it.Babu.
↧
sqlparser parseresult - How do you parse?
I was looking for some sample code to figure out how to effectively use some of the classes in the Microsoft.SqlServer.Management.SqlParser namespace. But to my astonishment, after googling for two entire days, couldn't find even one single sample code that shows what to do with the ParseResult instance returned by the Parse() method. MSDN and Technet both have only the definitions for these classes and methods. But not one single example of how to use them.Here is what I am trying to do. I am trying to design an User interface (similar to the SSMS query designer) when a user can look at the query graphically (again, similar to SSMS), modify the query graphically or directly in sql text and execute it. Here is the sql for AdventureWorks View object "vEmployee" for example.SELECT e.EmployeeID, c.Title, c.FirstName, c.MiddleName, c.LastName, c.Suffix, e.Title AS JobTitle, c.Phone, c.EmailAddress, c.EmailPromotion, a.AddressLine1, a.AddressLine2, a.City, sp.Name AS StateProvinceName, a.PostalCode, cr.Name AS CountryRegionName, c.AdditionalContactInfoFROM HumanResources.Employee AS e INNER JOIN Person.Contact AS c ON c.ContactID = e.ContactID INNER JOIN HumanResources.EmployeeAddress AS ea ON e.EmployeeID = ea.EmployeeID INNER JOIN Person.Address AS a ON ea.AddressID = a.AddressID INNER JOIN Person.StateProvince AS sp ON sp.StateProvinceID = a.StateProvinceID INNER JOIN Person.CountryRegion AS cr ON cr.CountryRegionCode = sp.CountryRegionCodeUsing SqlParser or the DependencyTree classes in SqlServer.Management namespaces, how can I parse the tokens out of the View. I need to be able to individually identify the columns, tables, join types, aliases, where clause conditions etc. I know all these information is available as tokens somewhere in either the View object or on the Database. I was able to retrieve all the columns and the dependant table names by walking dependencytree. But I can't figure out how to extract the other items. Without all the items, I won't be able to reconstruct the sql when a user graphically modifies the query. I can really use some sample code (C#, VB.NET, doesn't matter).Babu.
↧
↧
Schedule SQLExpress Backup using SQLDMO
is it possible to Schedule SQLExpress Backup using SQLDMO?SQL Express does not support SQL Agent then how can I view jobs created using SQLDMO?In management studio there is jobs option is unavailable. I have written code to add JObSchedule/job/jobStep and program is running without errors .. but no way to find out whether job is actually created and executed..
↧
Script difference between two databases
I need to compare two databases and update one of them. Suppose a table "Table A" is available in both databases but some columns are missing in the other table and I want to create an update sql script to update one database.I can add columns to the database to update and capture script by changing the execution mode, but the question is:How can I clone the column from one table to the other. I need to add the column as is with all constraints(i.e.) the exact copy of the other column.Any method of scripting the differences such that the resulting script with update the other table or all objects in the other database thus resulting in exactly the same databases.Any help will be appreciated.
↧
Process profiler log in C#
I am in charge of migration DB from 2k5 to 2k8One of tests to check that all functionality works same way in 2k8 as in 2k5 is “playing” trace file log on 2k5 and 2k8 in parallel and compare result for each statement as well as end result of database.Because DB in heavy usage for period of 8 hours it generates about 140 files 50MB each. I would like to write some code which will do same what profiler does when you open trace file set some filter like DatabaseId and then using menuFile/Export/Extract SQL Server Events/Extract Transact-SQL Eventsto get script file.In my research I only found only articles how to read trace file using Microsoft.Sqlserver.Managment,Trace.TraceFile object. But in this case I have to also build logic which will figure one line out approximately four in trace fileE.g. simple call for SP creates four events- RPC Started -SP Started-SP completed-RPC completedIf any other events happened in between of those four you have process them accordingly and create separate statement in script.SQL Profiler when extracts Transact-SQL Event does all job on it is own. I would appreciate if somebody points me how I can achieve same from code (I need process a lot of trace file) using posible kow figured method of TraceFile or something esleAlternatively I can put tarce file into table using fn_trace_gettable but again will have to figure how query table to generate SQL scriptThanks!Thanks!
↧
Using SQLCMD script in SMO
Hello,I have a C# program which uses SMO to submit tsql to SQL Server 2008 R2 for execution. The tsql is read in from a script file and this works fine.However if I give it a script file which contains some sqlcmd syntax I get an exception saying "Incorrect syntax near ':' .Is it the case that SMO does not support script files with sqlcmd syntax?If that is the case, please can anyone you suggest alternatives.Thank you,Anil.
↧
↧
SMO Backup event PercentCompleteEventHandler not fired
Hi,When I run this code, the event PercentCompleteEventHandler (Backup_PercentComplete); never fired.Then event ServerMessageEventHandler(Backup_Complete) is firedwhen the backup is complete.The backup operation run Ok and without errors.Runnig with vs 2008 and sql server 2008 r2 RTMObjects SMO version 10.0.0.0Any ideas?The code:using System; using System.Data; using System.Collections; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; class Program { static void Main(string[] args) { BackupDeviceItem bdi = new BackupDeviceItem(@"c:\temp\MyDB.bak", DeviceType.File); Backup bu = new Backup( ); bu.Database ="MyDB"; bu.Devices.Add(bdi); bu.Initialize =true; bu.PercentCompleteNotification = 10; // add percent complete and complete event handlers bu.PercentComplete += new PercentCompleteEventHandler(Backup_PercentComplete); bu.Complete += new ServerMessageEventHandler(Backup_Complete); Server server = new Server("localhost"); bu.SqlBackup(server); Console.WriteLine(Environment.NewLine + "Press any key to continue."); Console.ReadKey( ); } protected static void Backup_PercentComplete( object sender, PercentCompleteEventArgs e) { Console.WriteLine(Environment.NewLine + e.Percent + "% processed."); } protected static void Backup_Complete(object sender, ServerMessageEventArgs e) { Console.WriteLine(Environment.NewLine + e.ToString( )); }}
↧
sqlcmd.exe is hanging after running sql statement in inno package
Hello,I'm write installation package using inno for ms sql script. I have the following code:[code="other"] strParam := '-U hel -P password -S ServerName -d test -Q "sp_test"'; try Exec('sqlcmd.exe', strParam, '', SW_SHOW, ewWaitUntilTerminated, ResultCode); result := ResultCode = 0; except Exec('osql.exe', strParam, '', SW_SHOW, ewWaitUntilTerminated, ResultCode); result := ResultCode = 0; end;[/code]Sp executes ok but black screen with sqlcmd.exe is hanging until either I type exit or close it. I want a window with sqlcmd.exe closed after sp is executed.
↧
SQL Server Denali SMO calls with .NET framework 3.5
Hi,Does SMO expect .Netframework 4.0 to talk to SQL server Denali or 3.5 is enough?I'm trying to migrate my C#, .Net application to support SQL Server Denali. The application currently supports SQL Sever 2008 and uses .Net Framework 3.5. I'm just wondering if just replacing SMO assemblies (as per http://msdn.microsoft.com/en-us/library/dd206977%28v=sql.110%29.aspx) are enough or do I need to migrate to .Net framework 4.0 too. SQL server Denali expects 4.0 to work but SMO library does not talk about the framework to be used. When I try to remotely connect to the Denali server using framework 3.5 I get the following error."System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"Thanks for the help,Hem
↧
Using SMO for 2000 servers
Hi Friends,I would like to know how can I take full advantage of SMO scripting on SQL Server 2000 too.I have a working script of SMO for 2005 servers. I know that DMO is the one for 2000, but I believe SMO has a backward compatibility as well?On the other hand, I tried importing SQLDMO dll into the SSIS script task to write separate code for 2000, but SSIS could not utilize its functionality.Thanks in advance :)
↧
↧
how to call excel (2007/2010) macro in SSIS Package (2005/2008)
Hello,My situation : - Excel 2007 and 2010MSBI - 2005 and 2008 (EE/SE)Excel based macro has been written in above mentioned versions of excel.Script Task : - marco would copy and paste data from different sheets of 3 different excel files to one sheet to make it one consolidated data.Requirement : - Need to run those macros using SSIS on the excel file.Please send me step by step process to do it. Rgds,Pankaj
↧
Minimum permissions to allow access to SMO.Server.Databases.Users list
I have a Powershell script which I would like to run using less than sysadmin permissions.It creates a New-Object Microsoft.SqlServer.Management.Smo.ServerThen uses FOREACH-OBJECT in the Databases collectionThen uses FOREACH-OBJECT in the Users collection, grabs the name and the loginThis is ok for a sysadmin account, but for an ordinary user I get an exceptionThe following exception was thrown when trying to enumerate the collection: "An exception occurred while executing a Transact-SQL statement or batch.".At line:1 char:4+ $_. <<<< Users + CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException + FullyQualifiedErrorId : ExceptionInGetEnumeratorPublic server role gives access to the list of databases, is there a server setting which will give me access to the users in a database?Sorry if the question is a bit garbled; it's tired and I'm getting late. Thanks for your help.
↧
Detach database, copy to new location, attach database
Hello,PowerShell newbie here. I'm trying to write a PS script that will detach a database, copy the data and log files to new location, and attach database using new file location. I'm stuck on getting the current physical file names. Here is the code I have so far:[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | out-null[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlEnum") | out-null$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList 'BRETTW7'$database = $server.Databases['Test1'];$dblogfiles = $database.LogFiles.Item(0).Name;Write-Host 1: $dblogfiles ;$fileToRename = $database.FileGroups["PRIMARY"].Files[$dblogfiles];write-host 2: $database.FileGroups.get_Item(0).FilesWrite-Host 3: $fileToRename ;Write-Host 4: $initialpath;So -- how do I get the physical file name of the data and log files?Also, does anyone have any scripts or snippets that would help me?Thank you in advance.Brett
↧
SSIS Vs Linked Server with SQL Agent Jobs
Dear Experts,Need advice in planning. There are tables which needs to be exported to / imported from databases on different SQL instances DAILY and also want to have exception handlers or notifications of the daily run and the status (especially on failure of perticular table). Please let me know whether to go with SSIS or create a linked server and schedule Job also let me know the advantages and disadvantages over both. At the max the below steps will be involved:1. Drop the existing tables at destination2. Create Tables at destination3. Insert Data at destination.
↧
↧
Programming the Data Conversion task in SQL Server Integration Services 2012 in C#
I am trying to adapt C# code that configures the Data Conversion task from the code used in SQL 2005 and 2008 to 2012. Many things seem to have changed, and I am unable to figure out how to correctly assign the properties for the input->output path in the Conversion task. The following code worked for 2005 and 2008:[code="other"] IDTSPath90 path = this.mainPipe.PathCollection.New(); path.AttachPathAndPropagateNotifications(sourceComponent.OutputCollection[0], convComponent.InputCollection[0]); IDTSInput90 input = convComponent.InputCollection[0]; IDTSVirtualInput90 virtualInput = input.GetVirtualInput(); //Binder start og converted sammen. VirtualInput på converted er output på start foreach (ModelColumnTransformation columnTransformation in transformation.Transfers) { foreach (IDTSVirtualInputColumn90 virtualColumn in virtualInput.VirtualInputColumnCollection) { if (string.Compare(virtualColumn.Name, columnTransformation.FromColumn.Name, true) == 0 || (columnTransformation.FromColumn.Preformatted && columnTransformation.FromColumn.Name.EndsWith(" as \"" + virtualColumn.Name + "\""))) { convInstance.SetUsageType(input.ID, virtualInput, virtualColumn.LineageID, DTSUsageType.UT_READONLY); IDTSOutputColumn90 outputColumn = convComponent.OutputCollection[0].OutputColumnCollection.New(); outputColumn.Name = virtualColumn.Name + " (Converted)"; outputColumn.SetDataTypeProperties(columnTransformation.ToColumn.DataType, columnTransformation.ToColumn.Length, columnTransformation.ToColumn.Precision, columnTransformation.ToColumn.Scale, 0); outputColumn.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent; outputColumn.TruncationRowDisposition = DTSRowDisposition.RD_IgnoreFailure; IDTSCustomProperty90 outputProp = outputColumn.CustomPropertyCollection.New(); outputProp.Name = "SourceInputColumnLineageID";//I expect this line to be the problem outputProp.Value = virtualColumn.LineageID;//I expect this line to be the problem outputProp = outputColumn.CustomPropertyCollection.New(); outputProp.Name = "FastParse"; outputProp.Value = false; break; } } }[/code]Apparently, the inner workings of the LineageID property has changed, and if I look at the SSIS format, the LineageID now needs to be a "logical" string instead of an integer ID. I have been unable to figure out where to obtain this ID in the objects and assign it in the transition from input to output.
↧
SMO compatibility error
Is anyone aware of any forward compatibility bug in the SMO library?We are having an issue with a .NET client using SMO to check for create database permission. It seems to have trouble reading the 2008 R2 library when communicating with SQL 2012.
↧
SMO.Scripter: Help Walking a DependencyCollection
Hi there I am working on automating the process of scripting creates for our SQL Views and object dependencies of the views (namely functions in this case). I don't care about table dependencies. I was able to easily script the objects not in dependency order, but I am struggling with walking the dependency tree in my code.Here is where I am so far. You can see in the last loop (blank) that I am struggling. Would someone be so kind as to point me in the appropriate direction?[code="plain"] //Trying to Connect to Source Database and Server Server SrcServerCon = new Server(SrcServer); SrcServerCon.ConnectionContext.LoginSecure = Convert.ToBoolean(isWindowsAuth); try { if (SrcServerCon.ConnectionContext.LoginSecure == false) { SrcServerCon.ConnectionContext.Login = SQLAuthLogin; SrcServerCon.ConnectionContext.Password = SQLAuthPword; } } catch (Exception sqlConnect) { using (System.IO.StreamWriter exAtvws = new System.IO.StreamWriter(Logger, true)) { exAtvws.WriteLine("SQLConnect - " + DateTime.Now.ToString() + "-" + sqlConnect.Message ); } Environment.Exit(1); } Scripter vwScripter = new Scripter(SrcServerCon); //Initiating Scripter Constructor vwScripter.Options = new ScriptingOptions(); vwScripter.Options.ScriptDrops = true; vwScripter.Options.IncludeIfNotExists = true; vwScripter.Options.SchemaQualify = true; vwScripter.Options.WithDependencies = true; vwScripter.Options.NoCollation = true; //Deleteing the File if it exists in the target location if (System.IO.File.Exists(ScriptOutputLoc)) { System.IO.File.Delete(ScriptOutputLoc); } try { Database SrcDbCOn = SrcServerCon.Databases[SrcDbName]; //Adding UDFs and Vws to Urn Collection UrnCollection udfobjs = new UrnCollection(); foreach (UserDefinedFunction udf in SrcDbCOn.UserDefinedFunctions) { if (!udf.IsSystemObject) { udfobjs.Add(udf.Urn); } } foreach (View views in SrcDbCOn.Views) { if (!views.IsSystemObject) { udfobjs.Add(views.Urn); } } //Creating Dependency Tree DependencyTree dtree = vwScripter.DiscoverDependencies(udfobjs, true); DependencyWalker dwalker = new DependencyWalker(); DependencyCollection dcollect = dwalker.WalkDependencies(dtree); using (System.IO.StreamWriter FxscriptsToFile = new System.IO.StreamWriter(ScriptOutputLoc, true)) { foreach (DependencyCollectionNode dcoln in dcollect) { }[/code]
↧