Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Thursday, March 29, 2012

Edit and Continue while Debugging Script Task

Hi all,

I have a simple question: is it possible to use Edit and Continue feature when debugging a script task in VSA?

It seems to me that after breaking the execution of the script task and adding some code in break mode, whole edit disappears after leaving VSA environment.

I have enjoyed the Edit and Continue feature when developing in VBA, so I am wondering if it is available in VSA.

Thank you very much for the answer!

Marek Stefanek

Hi Marek,

Though you can re -debug from your edit point, SSIS is designed not to allow changes to be saved during runtime. So better copy all the changes you do into an editor before exiting from the Debug mode

Thanks

Subhash Subramanyam

|||

Thank you, Subhash.

Although it is not a good news for me, at least it saved me from time consuming searching on the web :-)

Regards,

Marek

Echo sql which has been run

I am relatively new to SQL Server.

I have a command file with the following contents :
osql -E -i%1.sql -d%2 -oq:\%1.log

The sql script file has a number of insert/update statements.
The log file produced looks something like this :

1> 2> (1 row affected)
1> 2> (1 row affected)
1> 2> (0 rows affected)

Is there any setting which can be turned on such that the log file
produced from this command file will echo the statement and then
the number of rows which are affected.

TIA."Michael McGarrigle" <mjm@.barwonwater.vic.gov.au> wrote in message
news:9d0cafdc.0309111717.4dc8efaa@.posting.google.c om...
> I am relatively new to SQL Server.
> I have a command file with the following contents :
> osql -E -i%1.sql -d%2 -oq:\%1.log
> The sql script file has a number of insert/update statements.
> The log file produced looks something like this :
> 1> 2> (1 row affected)
> 1> 2> (1 row affected)
> 1> 2> (0 rows affected)
> Is there any setting which can be turned on such that the log file
> produced from this command file will echo the statement and then
> the number of rows which are affected.
> TIA.

You can try adding -e -n to your command line. It works best if each
statement is in its own batch:

update...
go
insert...
go

Like that, you get each statement with the rowcount immediately after it. If
all statements are in one batch, you'll get all the statements together then
all the rowcounts together. That might be OK for you anyway, of course.

Simonsql

Echo for SQL scripts

Hi all,

I want to see input SQL statements in the log file when I run the script in SQLPlus. I have used this set command "SET ECHO ON" for this. However, the log file looks like this -

drop table table_A
*
ERROR at line 1:
ORA-00942: table or view does not exist

7444 rows deleted.

Commit complete.

Thus, the SQL statement is not visible if it is error free. Is there a way to get around this?

ThanksDid you try to SPOOL the results?
This will do it:
SET ECHO ON
SPOOL logfile.log
@.MyScript
SPOOL OFF
;)|||I added these commands in my script -

set echo on
spool log_file.log
@.script_name.sql
spool off

the log file only had this error message -

SP2-0309: SQL*Plus command procedures may only be nested to a depth of 20.|||I added these commands in my script -

set echo on
spool log_file.log
@.script_name.sql
spool off

the log file only had this error message -

SP2-0309: SQL*Plus command procedures may only be nested to a depth of 20.

This error means what it means: your script executes a script that executes a script ...etc upto more that 20 levels deep.
:rolleyes:

easy way to mark all the fk's and triggers NFR?

Is there a script somehwhere which would alter all constraints and
recreate/alter triggers with NFR property set to 1?
or
would one of you guys know of an easy way to do it?
Thank you.
Tejas.
Following should help. PLEASE TEST IT BEFORE USING IT IN A REAL ENVIRONMENT.
You may uncomment the commented lines if trying to do the same for individual
tables.
SET NOCOUNT ON
GO
DECLARE@.tbl_namevarchar(50)
--SELECT@.tbl_name = 'tbl_name'
/*
Creating the command to drop constraints on the table
*/
SELECT'ALTER TABLE ' + object_name(fkeyid) + ' DROP CONSTRAINT ' +
object_name(constid) + CHAR(10) + 'GO' + CHAR(10)
FROMsysreferences
-- WHERE object_name(fkeyid) = @.tbl_name
-- ORobject_name(rkeyid) = @.tbl_name
ORDER BY object_name(fkeyid)
/*
Creating the command to re-create all the dropped constraints
*/
SELECT'ALTER TABLE ' + object_name(a.fkeyid) + ' ADD CONSTRAINT ' +
object_name(constid) + ' FOREIGN KEY (' + b.name + ') REFERENCES ' +
object_name(a.rkeyid) + '(' + c.name + ') NOT FOR REPLICATION' + CHAR(10) +
'GO' + CHAR(10)
FROM sysforeignkeys a,
syscolumns b,
syscolumns c
WHERE a.fkey = b.colid
AND a.fkeyid = b.id
AND a.rkey = c.colid
AND a.rkeyid = c.id
-- AND (object_name(a.rkeyid) = @.tbl_nameOR
-- object_name(a.fkeyid) = @.tbl_name)
ORDER BY object_name(a.fkeyid)
GO
"Tejas Parikh" wrote:

> Is there a script somehwhere which would alter all constraints and
> recreate/alter triggers with NFR property set to 1?
> or
> would one of you guys know of an easy way to do it?
> Thank you.
> Tejas.

Wednesday, March 21, 2012

dynamically switching databases in a script

I've got a situation where I need to execute portions of a script against every database on a given instance. I don't know the name of all the databases beforehand so I need to scroll through them all and call the "use" command appropriately.

I need the correct syntax, the following won't work:

DECLARE DBS CURSOR FOR
SELECT dbname
FROM #helpdb
ORDER BY dbname

OPEN DBS

FETCH NEXT
FROM DBS
INTO
@.dbname

WHILE @.@.FETCH_STATUS = 0
BEGIN

USE @.dbname

The last line - the "USE" statement - is invalid. The following for example works:

USE master

But when supplied a declared variable a syntax error results for the use command because it expects an identifier.

So .. what is the correct syntax to pass a declared parameter to "USE", or is there another way to meet this requirement?

Thanks for your time.

This is not possible right now since you cannot use variables in lot of statements in place of options or identifiers. You can use dynamic SQL though and below is the easiest way to do it:

declare @.sp nvarchar(500)

...

while .....

begin

-- use dbo.sp_executesql for SQL Server 2000

set @.sp = quotename(@.dbname) + N'sys.sp_executesql'

exec @.sp N'your sql string that needs to execute against db'

...

end

|||although this allowed the "use .." statement to run, it didn't have the effect I need. The remainder of the script was still running in the context of the original database.|||

So here's what I really need:

I need a way to switch the context of a script from one database to another, where I do not know the name of the databases beforehand (so they can't be hard-coded).

|||What I suggested will work provided the code that you want to run within context of the database is executed dynamically. Another approach is to pre-process the script file based on the database name and then run it. With SQL Server 2005, you can do this using SQLCMD pre-processing features.

Sunday, March 11, 2012

Dynamically create text file as destination from sql script in SSIS

I have a select Script as follows:

SELECT c.ABC AS 'ABC'

, a.Qty AS 'Quantity_Recived'

, b.PC AS 'PC'

, b.PC AS 'PC'

, 'I' AS 'Flag'

FROM TNRInventory.dbo.tInventoryAlloc AS a

LEFT OUTER JOIN vwInventoryAllocMapping AS vwMap ON a.TNRAllocTypeID = vwMap.TNRInventoryAllocID

LEFT OUTER JOIN ABC.dbo.ZREFRESHTAB AS b ON a.DispenserID = b.Asset

LEFT OUTER JOIN ABC.dbo.TableJoinKey AS c ON a.TitleID = c.TITLE_ID

WHERE (vwMap.DataSourceID = 3) and vwMap.[DataSourceAllocName] = 'I'

group by c.SKU_NO , vwMap.[DataSourceAllocName],a.Qty , b.Profit_Center

order by c.SKU_NO,vwMap.[DataSourceAllocName]

GO

i have to send the result of aforesaid script in batch of 300 records per file (tab delimited text file)
now the file name must be dynamically created as each file will contain 300 records.

I have found some document related to same issue on this url

http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=1238184&SiteID=17

but still there is a catch.

Can any one guide/suggest me better way to do the aforesaid.

Thanks

Thinking while typing, this could be done with a few steps.

1 - Data Flow - Load a staging table with the results of the SQL. Add to it a row number counter so that every row is numbered uniquely.

2 - Control Flow - Run an Execute SQL Task to select max(rownumber) from that staging table

3 - Control Flow - Use a script task to take the output of the Execute SQL task and populate another variable with the number of iterations needed to populate files with up to 300 rows. (max(rownumber) / 300 - if no remainder, use that value, if remainder add one to the integer, etc...)

4 - Control Flow - Use a for loop to iterate the output variable from step 3 above.

5 - Control Flow - Build a variable set to an expression to use a base filename and the variable from step 3 above.

6 - Control Flow For Loop - Loop through the variable from step 3 above and add a data flow. Inside this data flow, use an OLE DB (or whatever) to connect to the staging table from step 1, filtering by (variable_step3 * 300) you can select just the records for this iteration. Hook that up to a flat file destination, which uses expressions to set the file name equal to the variable from step 5 above.

Something like that.|||

You might also check Jamie's blog post on this topic.

http://blogs.conchango.com/jamiethomson/archive/2005/12/04/SSIS-Nugget_3A00_-Splitting-a-file-into-multiple-files.aspx

Essentially the same technique that Phil recommended, but he's got some sample code already

|||

jwelch wrote:

You might also check Jamie's blog post on this topic.

http://blogs.conchango.com/jamiethomson/archive/2005/12/04/SSIS-Nugget_3A00_-Splitting-a-file-into-multiple-files.aspx

Essentially the same technique that Phil recommended, but he's got some sample code already

D'oh! Should've just looked there first!|||

What i did is i create a view for aforesaid script and then used that script in the following VB.net script

' Microsoft SQL Server Integration Services Script Task

' Write scripts using Microsoft Visual Basic

' The ScriptMain class is the entry point of the Script Task.

Imports System

Imports System.Data

Imports System.Math

Imports Microsoft.SqlServer.Dts.Runtime

Imports System.Data.SqlClient

Imports System.Text

Imports System.IO

Public Class ScriptMain

Public Sub Main()

Dim ConnectionString As String = "Server=ServerName;Database=DatabaseName;uid=Login;pwd=Password;"

Dim querystring As String = "SELECT * FROM vwInventory_I"

Dim con As New SqlConnection(ConnectionString)

Dim adapter As New SqlDataAdapter()

Dim ds As New DataSet

Dim dt As New DataTable

adapter.SelectCommand = New SqlCommand(querystring, con)

adapter.Fill(ds)

dt = ds.Tables(0)

CreateFile(dt)

End Sub

Private Sub CreateFile( ByVal table As DataTable)

Dim intRowCount As Integer = table.Rows.Count

Dim Column1Value As String

Dim Column2Value As String

Dim Column3Value As String

Dim Column4Value As String

Dim Column5Value As String

Dim sb As New StringBuilder

Dim seperator As String = vbTab

Dim nFileNameCount As Integer

nFileNameCount = 0

'For i As Integer = 0 To table.Columns.Count - 1

Dim i As Integer = 0

Dim j As Integer = 0

For j = 0 To intRowCount - 1

If nFileNameCount = 100 Then

PrintFile(sb, j)

'clears the stringbuilder

sb.Remove(0, sb.ToString.Length - 1)

nFileNameCount = 0

End If

Column1Value = table.Rows(j)(i).ToString

Column2Value = table.Rows(j)(i + 1).ToString

Column3Value = table.Rows(j)(i + 2).ToString

Column4Value = table.Rows(j)(i + 3).ToString

Column5Value = table.Rows(j)(i + 4).ToString

sb.Append(Column1Value & seperator & Column2Value & seperator & Column3Value & seperator & _

Column4Value & seperator & Column5Value & seperator & vbCrLf)

nFileNameCount = nFileNameCount + 1

Next

PrintFile(sb, j)

'Next

End Sub

Private Sub PrintFile( ByVal sb As StringBuilder, ByVal recordcount As Integer)

' Create an instance of StreamWriter to write text to a file.

Dim strDate As String

strDate = String.Format("{0:yyyy}" , DateTime.Now)

strDate = strDate & String.Format( "{0:MM}", DateTime.Now)

strDate = strDate & String.Format( "{0d}", DateTime.Now)

Using sw As StreamWriter = New StreamWriter("C:\SSIS\I_" & strDate & "_" & recordcount & ".txt")

sw.WriteLine(sb.ToString)

sw.Close()

End Using

'this will create a text file in bin directory

End Sub

End Class

This is how you generate tab delimited files to test check Use Script Tas from SSIS

|||Uh, okay. Good. So why even use SSIS then? Write your own program as you have done, compile it, and execute the resulting binary file. Leave the bloat of SSIS out of it.|||

I am going to put this piece in middle of my design.

It was the one of the key to finish my jik-so-puzzle.

Other one is to delete the files from Unix Aix Server with FTP connection.

And here too I have to go all the way round, as there FTP connection works fine on Microsoft server but not on UNIX server.

It does not allow you to delete the files on UNIX server.

That is the reason I am using the code in SSIS.

Friday, March 9, 2012

Dynamically Choose Database

I have to write a large data migration script to move data from one SQL Server database to another. Is there any way to dynamically specify the server and database name? I would like to do something like the following, (but this does not seem to work):

Delete From [@.ServerName].[@.ImportToDatabase].[MyTable]

Any help appreciatedno. you can't do that.

EXECUTE 'DELETE FROM [' + @.ServerName + '].[' + @.ImportToDatabase + '].[username].[MyTable]'|||For some reason this doesn't seem to work in my code. However using:

EXEC ('DELETE FROM [' + @.ServerName + '].[' + @.ImportToDatabase + '].[username].[MyTable]' )

Does work.

Thanks for your comments

Sunday, February 26, 2012

Dynamic USE

I want to run a .sql script that updates data from specific tables using
OSQL. The problem i am having is that i need to run the same script on 300
servers. The database naming scheme are as follows:
server 1 : server1_testdb
server 2 : server2_testdb
server 3: server3_testdb
Question:
How can I write one script that can be used for all 300 servers. All
databases have the same structure and are identical except that it resides in
300 servers that is where the prefix (server1_, server2_, etc.) come from.
Does it mean I have to write 300 scripts to specify the database where the
script will be run.
Ex.
script 1: USE server1_testdb
UPDATE tbl_sample ...
script 2: USE server2_testdb
UPDATE tbl_sample ...
script 3: USE server3_testdb
UPDATE tbl_sample ...
Is there a way to employ the 'USE' statement dynamically? Is there a way to
pass a variable to the USE statement such as:
DECLARE @.sampledb sysname
SELECT @.sampledb = master.sysdatabases.name.........
USE @.sampledb
Help highly appreciated.
Looks to me like you should do this with SMO (SQL 2005) or DMO (earlier).
In both cases, your connect strings will determine which server/DB to use.
At that point, it's all SQL.
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA, MCITP, MCTS
SQL Server MVP
Toronto, ON Canada
https://mvp.support.microsoft.com/profile/Tom.Moreau
"morphius" <morphius@.discussions.microsoft.com> wrote in message
news:24723016-1F59-4B31-A779-988ECA6EA444@.microsoft.com...
I want to run a .sql script that updates data from specific tables using
OSQL. The problem i am having is that i need to run the same script on 300
servers. The database naming scheme are as follows:
server 1 : server1_testdb
server 2 : server2_testdb
server 3: server3_testdb
Question:
How can I write one script that can be used for all 300 servers. All
databases have the same structure and are identical except that it resides
in
300 servers that is where the prefix (server1_, server2_, etc.) come from.
Does it mean I have to write 300 scripts to specify the database where the
script will be run.
Ex.
script 1: USE server1_testdb
UPDATE tbl_sample ...
script 2: USE server2_testdb
UPDATE tbl_sample ...
script 3: USE server3_testdb
UPDATE tbl_sample ...
Is there a way to employ the 'USE' statement dynamically? Is there a way to
pass a variable to the USE statement such as:
DECLARE @.sampledb sysname
SELECT @.sampledb = master.sysdatabases.name.........
USE @.sampledb
Help highly appreciated.
|||If you have SQL Server 2005 among your servers and all your servers are
visible from the server with SQL Server 2005 installed use SQLCMD
command-line utility and its features combined with some simple Windows
shell commands.
Create a sql script (save it as script.sql) like:
USE $(dbname)
GO
UPDATE ... -- put your statement here
Create simple Windows batch (save it as batch.bat in the same location as
script.sql) like:
for /L %%n IN (1,1,300) DO sqlcmd -S server%%n -E -v
dbname=server%%n_testdb -i script.sql
Then just run the batch and you should get what you want. I assume that you
have the same Windows login on all SQL Server instances.
Let me know if it works.
Regards
Pawel Potasinski
[http://www.potasinski.pl]
Uytkownik "morphius" <morphius@.discussions.microsoft.com> napisa w
wiadomoci news:24723016-1F59-4B31-A779-988ECA6EA444@.microsoft.com...
>I want to run a .sql script that updates data from specific tables using
> OSQL. The problem i am having is that i need to run the same script on
> 300
> servers. The database naming scheme are as follows:
> server 1 : server1_testdb
> server 2 : server2_testdb
> server 3: server3_testdb
> Question:
> How can I write one script that can be used for all 300 servers. All
> databases have the same structure and are identical except that it resides
> in
> 300 servers that is where the prefix (server1_, server2_, etc.) come from.
> Does it mean I have to write 300 scripts to specify the database where the
> script will be run.
> Ex.
> script 1: USE server1_testdb
> UPDATE tbl_sample ...
> script 2: USE server2_testdb
> UPDATE tbl_sample ...
> script 3: USE server3_testdb
> UPDATE tbl_sample ...
> Is there a way to employ the 'USE' statement dynamically? Is there a way
> to
> pass a variable to the USE statement such as:
> DECLARE @.sampledb sysname
> SELECT @.sampledb = master.sysdatabases.name.........
> USE @.sampledb
> Help highly appreciated.
>

Dynamic USE

I want to run a .sql script that updates data from specific tables using
OSQL. The problem i am having is that i need to run the same script on 300
servers. The database naming scheme are as follows:
server 1 : server1_testdb
server 2 : server2_testdb
server 3: server3_testdb
Question:
How can I write one script that can be used for all 300 servers. All
databases have the same structure and are identical except that it resides in
300 servers that is where the prefix (server1_, server2_, etc.) come from.
Does it mean I have to write 300 scripts to specify the database where the
script will be run.
Ex.
script 1: USE server1_testdb
UPDATE tbl_sample ...
script 2: USE server2_testdb
UPDATE tbl_sample ...
script 3: USE server3_testdb
UPDATE tbl_sample ...
Is there a way to employ the 'USE' statement dynamically? Is there a way to
pass a variable to the USE statement such as:
DECLARE @.sampledb sysname
SELECT @.sampledb = master.sysdatabases.name.........
USE @.sampledb
Help highly appreciated.Looks to me like you should do this with SMO (SQL 2005) or DMO (earlier).
In both cases, your connect strings will determine which server/DB to use.
At that point, it's all SQL.
--
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA, MCITP, MCTS
SQL Server MVP
Toronto, ON Canada
https://mvp.support.microsoft.com/profile/Tom.Moreau
"morphius" <morphius@.discussions.microsoft.com> wrote in message
news:24723016-1F59-4B31-A779-988ECA6EA444@.microsoft.com...
I want to run a .sql script that updates data from specific tables using
OSQL. The problem i am having is that i need to run the same script on 300
servers. The database naming scheme are as follows:
server 1 : server1_testdb
server 2 : server2_testdb
server 3: server3_testdb
Question:
How can I write one script that can be used for all 300 servers. All
databases have the same structure and are identical except that it resides
in
300 servers that is where the prefix (server1_, server2_, etc.) come from.
Does it mean I have to write 300 scripts to specify the database where the
script will be run.
Ex.
script 1: USE server1_testdb
UPDATE tbl_sample ...
script 2: USE server2_testdb
UPDATE tbl_sample ...
script 3: USE server3_testdb
UPDATE tbl_sample ...
Is there a way to employ the 'USE' statement dynamically? Is there a way to
pass a variable to the USE statement such as:
DECLARE @.sampledb sysname
SELECT @.sampledb = master.sysdatabases.name.........
USE @.sampledb
Help highly appreciated.|||If you have SQL Server 2005 among your servers and all your servers are
visible from the server with SQL Server 2005 installed use SQLCMD
command-line utility and its features combined with some simple Windows
shell commands.
Create a sql script (save it as script.sql) like:
USE $(dbname)
GO
UPDATE ... -- put your statement here
Create simple Windows batch (save it as batch.bat in the same location as
script.sql) like:
for /L %%n IN (1,1,300) DO sqlcmd -S server%%n -E -v
dbname=server%%n_testdb -i script.sql
Then just run the batch and you should get what you want. I assume that you
have the same Windows login on all SQL Server instances.
Let me know if it works.
--
Regards
Pawel Potasinski
[http://www.potasinski.pl]
U¿ytkownik "morphius" <morphius@.discussions.microsoft.com> napisa³ w
wiadomo¶ci news:24723016-1F59-4B31-A779-988ECA6EA444@.microsoft.com...
>I want to run a .sql script that updates data from specific tables using
> OSQL. The problem i am having is that i need to run the same script on
> 300
> servers. The database naming scheme are as follows:
> server 1 : server1_testdb
> server 2 : server2_testdb
> server 3: server3_testdb
> Question:
> How can I write one script that can be used for all 300 servers. All
> databases have the same structure and are identical except that it resides
> in
> 300 servers that is where the prefix (server1_, server2_, etc.) come from.
> Does it mean I have to write 300 scripts to specify the database where the
> script will be run.
> Ex.
> script 1: USE server1_testdb
> UPDATE tbl_sample ...
> script 2: USE server2_testdb
> UPDATE tbl_sample ...
> script 3: USE server3_testdb
> UPDATE tbl_sample ...
> Is there a way to employ the 'USE' statement dynamically? Is there a way
> to
> pass a variable to the USE statement such as:
> DECLARE @.sampledb sysname
> SELECT @.sampledb = master.sysdatabases.name.........
> USE @.sampledb
> Help highly appreciated.
>

Dynamic USE

I want to run a .sql script that updates data from specific tables using
OSQL. The problem i am having is that i need to run the same script on 300
servers. The database naming scheme are as follows:
server 1 : server1_testdb
server 2 : server2_testdb
server 3: server3_testdb
Question:
How can I write one script that can be used for all 300 servers. All
databases have the same structure and are identical except that it resides i
n
300 servers that is where the prefix (server1_, server2_, etc.) come from.
Does it mean I have to write 300 scripts to specify the database where the
script will be run.
Ex.
script 1: USE server1_testdb
UPDATE tbl_sample ...
script 2: USE server2_testdb
UPDATE tbl_sample ...
script 3: USE server3_testdb
UPDATE tbl_sample ...
Is there a way to employ the 'USE' statement dynamically? Is there a way to
pass a variable to the USE statement such as:
DECLARE @.sampledb sysname
SELECT @.sampledb = master.sysdatabases.name.........
USE @.sampledb
Help highly appreciated.Looks to me like you should do this with SMO (SQL 2005) or DMO (earlier).
In both cases, your connect strings will determine which server/DB to use.
At that point, it's all SQL.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA, MCITP, MCTS
SQL Server MVP
Toronto, ON Canada
https://mvp.support.microsoft.com/profile/Tom.Moreau
"morphius" <morphius@.discussions.microsoft.com> wrote in message
news:24723016-1F59-4B31-A779-988ECA6EA444@.microsoft.com...
I want to run a .sql script that updates data from specific tables using
OSQL. The problem i am having is that i need to run the same script on 300
servers. The database naming scheme are as follows:
server 1 : server1_testdb
server 2 : server2_testdb
server 3: server3_testdb
Question:
How can I write one script that can be used for all 300 servers. All
databases have the same structure and are identical except that it resides
in
300 servers that is where the prefix (server1_, server2_, etc.) come from.
Does it mean I have to write 300 scripts to specify the database where the
script will be run.
Ex.
script 1: USE server1_testdb
UPDATE tbl_sample ...
script 2: USE server2_testdb
UPDATE tbl_sample ...
script 3: USE server3_testdb
UPDATE tbl_sample ...
Is there a way to employ the 'USE' statement dynamically? Is there a way to
pass a variable to the USE statement such as:
DECLARE @.sampledb sysname
SELECT @.sampledb = master.sysdatabases.name.........
USE @.sampledb
Help highly appreciated.|||If you have SQL Server 2005 among your servers and all your servers are
visible from the server with SQL Server 2005 installed use SQLCMD
command-line utility and its features combined with some simple Windows
shell commands.
Create a sql script (save it as script.sql) like:
USE $(dbname)
GO
UPDATE ... -- put your statement here
Create simple Windows batch (save it as batch.bat in the same location as
script.sql) like:
for /L %%n IN (1,1,300) DO sqlcmd -S server%%n -E -v
dbname=server%%n_testdb -i script.sql
Then just run the batch and you should get what you want. I assume that you
have the same Windows login on all SQL Server instances.
Let me know if it works.
Regards
Pawel Potasinski
[http://www.potasinski.pl]
Uytkownik "morphius" <morphius@.discussions.microsoft.com> napisa w
wiadomoci news:24723016-1F59-4B31-A779-988ECA6EA444@.microsoft.com...
>I want to run a .sql script that updates data from specific tables using
> OSQL. The problem i am having is that i need to run the same script on
> 300
> servers. The database naming scheme are as follows:
> server 1 : server1_testdb
> server 2 : server2_testdb
> server 3: server3_testdb
> Question:
> How can I write one script that can be used for all 300 servers. All
> databases have the same structure and are identical except that it resides
> in
> 300 servers that is where the prefix (server1_, server2_, etc.) come from.
> Does it mean I have to write 300 scripts to specify the database where the
> script will be run.
> Ex.
> script 1: USE server1_testdb
> UPDATE tbl_sample ...
> script 2: USE server2_testdb
> UPDATE tbl_sample ...
> script 3: USE server3_testdb
> UPDATE tbl_sample ...
> Is there a way to employ the 'USE' statement dynamically? Is there a way
> to
> pass a variable to the USE statement such as:
> DECLARE @.sampledb sysname
> SELECT @.sampledb = master.sysdatabases.name.........
> USE @.sampledb
> Help highly appreciated.
>

Friday, February 24, 2012

Dynamic Text Parser?

Hi Guys,

I have a script task that is supposed to read and parse a fixed width source file.

Basically, I want to make the FieldWidths dynamic so that I'll be able to reuse this package with different files. So Instead of hardcoding the field widths directly into my script task, I want it to be stored somewhere that the package can get when executions starts. Is there a way of doing this?

The code looks like this:

Using Reader As New TextFieldParser(mTempFilePAth)

Reader.TextFieldType = FieldType.FixedWidth

Reader.SetFieldWidths(1, 8, 8, 8, 4, 8) <-- I want to change this to handle dynamic widths.

Hi,

The best way to make your package re-usable is to use a "Integration Services Variable", see this link for help on variables http://msdn2.microsoft.com/en-us/library/ms141085.aspx and this one for accessing from a script http://msdn2.microsoft.com/en-us/library/aa337079.aspx.

The main gotcha is you need to be aware of is this bit from the second link "You can make existing variables available for read-only or read/write

access by your custom script by entering comma-delimited lists of

variables in the ReadOnlyVariables and ReadWriteVariables fields on the Script page of the Script Transformation Editor."

Also does SetFieldWidths take a variable number of arguments? If so you may need to define a string SSIS variable with the arguments comma seperated, then parse them into the seperate arguments for SetFieldWidths

Dave

Wednesday, February 15, 2012

Dynamic SQL does not work!

I have a small SQL script that rotates through all databases on the
server and executes a Stored Procedure in each of them. Here are the
steps:
1: The first step is to get name of databases in to a cursor.
2: Build dynamic SQL to change database to database in variable - this
step fails
3: Execute SP
4: Move to next database.
Is it not possible to change current database using Dynamic SQL? Can
someone help me here please?

Here is the code I am using:
--EXECUTE SQL Statement on all Databases

DECLARE
@.DatabaseName varchar(100)
, @.SQL varchar(500)

DECLARE DBNameCursor CURSOR FOR
SELECT
[Name] AS DatabaseName
FROM
master.dbo.sysdatabases
ORDER BY
DatabaseName

OPEN DBNameCursor

FETCH NEXT FROM DBNameCursor
INTO @.DatabaseName

WHILE @.@.FETCH_STATUS = 0
BEGIN
--Change to Database
SELECT
@.SQL = 'USE ' + @.DatabaseName

EXEC(@.SQL)

--SQL Statement to be run
EXEC dbo.SPName

FETCH NEXT FROM DBNameCursor
INTO @.DatabaseName
END

CLOSE DBNameCursor
DEALLOCATE DBNameCursor

-------
Thanks in advance!
Vishal SinhaOn Feb 7, 7:02 am, "SQLJunkie" <vsinh...@.gmail.comwrote:

Quote:

Originally Posted by

I have a small SQL script that rotates through all databases on the
server and executes a Stored Procedure in each of them. Here are the
steps:
1: The first step is to get name of databases in to a cursor.
2: Build dynamic SQL to change database to database in variable - this
step fails
3: Execute SP
4: Move to next database.
Is it not possible to change current database using Dynamic SQL? Can
someone help me here please?
>
Here is the code I am using:
-- EXECUTE SQL Statement on all Databases
>
DECLARE
@.DatabaseName varchar(100)
, @.SQL varchar(500)
>
DECLARE DBNameCursor CURSOR FOR
SELECT
[Name] AS DatabaseName
FROM
master.dbo.sysdatabases
ORDER BY
DatabaseName
>
OPEN DBNameCursor
>
FETCH NEXT FROM DBNameCursor
INTO @.DatabaseName
>
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- Change to Database
SELECT
@.SQL = 'USE ' + @.DatabaseName
>
EXEC(@.SQL)
>
-- SQL Statement to be run
EXEC dbo.SPName
>
FETCH NEXT FROM DBNameCursor
INTO @.DatabaseName
END
>
CLOSE DBNameCursor
DEALLOCATE DBNameCursor
>
-------
Thanks in advance!
Vishal Sinha


If I recall correctly EXEC starts a new thread that won't know about
the preceeding USE statement.

My favorite dynamic SQL site:
http://www.sommarskog.se/dyn-search.html|||SQLJunkie (vsinha73@.gmail.com) writes:

Quote:

Originally Posted by

I have a small SQL script that rotates through all databases on the
server and executes a Stored Procedure in each of them. Here are the
steps:
1: The first step is to get name of databases in to a cursor.
2: Build dynamic SQL to change database to database in variable - this
step fails
3: Execute SP
4: Move to next database.
Is it not possible to change current database using Dynamic SQL? Can
someone help me here please?


Yes, but the effect of the USE lasts only for the duration of the of the
dynamic SQL.

Quote:

Originally Posted by

SELECT
@.SQL = 'USE ' + @.DatabaseName
>
EXEC(@.SQL)
>
-- SQL Statement to be run
EXEC dbo.SPName


If all you want to do is to run a stored procedure in each database,
this is the easiest way to do:

SELECT @.SPname = @.DatabaseName + '.dbo.SPName'
EXEC @.SPname

You may also be interested in sp_MSforeachdb:

EXEC sp_MSforeachdb 'EXEC ?.dbo.SPNAme'

This procedure is undocumented and unsupported, but it's nevertheless
fairly popular.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks everyone for the replies. The following example is fine for
generic SPs:
SELECT @.SPname = @.DatabaseName + '.dbo.SPName'
EXEC @.SPname

But what if I have to run SPs like SP_updatestats etc? then it will
not work.

Thanks!

On Feb 7, 5:35 pm, Erland Sommarskog <esq...@.sommarskog.sewrote:

Quote:

Originally Posted by

SQLJunkie (vsinh...@.gmail.com) writes:

Quote:

Originally Posted by

I have a small SQL script that rotates through all databases on the
server and executes a Stored Procedure in each of them. Here are the
steps:
1: The first step is to get name of databases in to a cursor.
2: Build dynamic SQL to change database to database in variable - this
step fails
3: Execute SP
4: Move to next database.
Is it not possible to change current database using Dynamic SQL? Can
someone help me here please?


>
Yes, but the effect of the USE lasts only for the duration of the of the
dynamic SQL.
>

Quote:

Originally Posted by

SELECT
@.SQL = 'USE ' + @.DatabaseName


>

Quote:

Originally Posted by

EXEC(@.SQL)


>

Quote:

Originally Posted by

-- SQL Statement to be run
EXEC dbo.SPName


>
If all you want to do is to run a stored procedure in each database,
this is the easiest way to do:
>
SELECT @.SPname = @.DatabaseName + '.dbo.SPName'
EXEC @.SPname
>
You may also be interested in sp_MSforeachdb:
>
EXEC sp_MSforeachdb 'EXEC ?.dbo.SPNAme'
>
This procedure is undocumented and unsupported, but it's nevertheless
fairly popular.
>
--
Erland Sommarskog, SQL Server MVP, esq...@.sommarskog.se
>
Books Online for SQL Server 2005 athttp://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books...
Books Online for SQL Server 2000 athttp://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

|||SQLJunkie (vsinha73@.gmail.com) writes:

Quote:

Originally Posted by

Thanks everyone for the replies. The following example is fine for
generic SPs:
SELECT @.SPname = @.DatabaseName + '.dbo.SPName'
EXEC @.SPname
>
But what if I have to run SPs like SP_updatestats etc? then it will
not work.


Au contraire, it will work just fine! If you say:

EXEC mydb..sp_systemprocedure

the system procedure will execute in the context of mydb.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks - it worked!

Momentary lapse of reason :)

On Feb 8, 5:39 pm, Erland Sommarskog <esq...@.sommarskog.sewrote:

Quote:

Originally Posted by

SQLJunkie (vsinh...@.gmail.com) writes:

Quote:

Originally Posted by

Thanks everyone for the replies. The following example is fine for
generic SPs:
SELECT @.SPname = @.DatabaseName + '.dbo.SPName'
EXEC @.SPname


>

Quote:

Originally Posted by

But what if I have to run SPs like SP_updatestats etc? then it will
not work.


>
Au contraire, it will work just fine! If you say:
>
EXEC mydb..sp_systemprocedure
>
the system procedure will execute in the context of mydb.
>
--
Erland Sommarskog, SQL Server MVP, esq...@.sommarskog.se
>
Books Online for SQL Server 2005 athttp://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books...
Books Online for SQL Server 2000 athttp://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

dynamic SQL Create Table

The following dynamic SQL script works for creating a table on the fly but if I change the select @.tmpTblNm = 'tmpABC' to select @.tmpTblNm = '#tmpABC'
it will not create the temp table. Can anyone help on creating a temp table dynamiclly?

declare @.tmpTblNm varchar(40),
@.str varchar(1000)

select @.tmpTblNm = 'tmpABC'
select @.str = ''

-- Create a temp table to hold the current page of data
-- Add an ID column to track the current row
select @.str = 'Create Table '+ @.tmpTblNm +
' ( row_id int IDENTITY PRIMARY KEY,
customerID int,
customerName varchar(40),
address1 varchar(40),
city varchar(25) )'

exec (@.str)The problem is that it did exactly what you requested, just not what you wanted.

A temporary table lasts for the duration of its creator. For a script, that is as long as you have the session open (until you close the session). For a stored procedure, the duration is as long as the procedure runs. For dynamic SQL, the duration is the dynamic execute.

When you build a temp table dynamically, the table exists for as long as the statement runs. You can use a global (aka ##) table, but that brings its own problems to play. You can create a table within your script or procedure, but then it isn't very dynamic.

-PatP

Dynamic SQL colunms into rows

Im trying to write a SQL script that will turn the rows from one table into colunms. I'm using the sp_excutesql porceure and it keeps coming back with an error.

The problem is that i cant seem to be able to use @.parameter as a name when i try to dynamically create a column. Its a dynamic sql problem but i cant seem to get around it.

This is the problem line -- SELECT @.SQL ='ALTER TABLE tblHM21 ADD @.ColName varchar(50)'

Create Table tblHM21 (uidHM21uniqueidentifier);-- loop through tests to get bring back names of the rows-- --declare @.rowCountintdeclare @.iintset @.i = 1set @.rowCount = (SELECTCount(intTestTableRow)FROM tblHSTests)while @.i <= @.rowCount
Begindeclare @.ColumnNamenvarchar(50)set @.columnName = (Select strTestNamefrom tblHStestswhere intTestTableRow = @.i)declare @.SQLnvarchar(500)declare @.paramsnvarchar(4000)SELECT @.SQL ='ALTER TABLE tblHM21 ADD @.ColName varchar(50)'SELECT @.params = N'@.ColName nvarchar(50)'EXECsp_executesql @.SQL, @.params, @.ColumnNameprint @.iprint @.ColumnNameset @.i = @.i+1Endselect *from tblHM21Drop Table tblHM21
hi

put

set@.SQL ='ALTER TABLE tblHM21 ADD @.ColName varchar(50)'
set @.params = N'@.ColName nvarchar(50)'
 
and before  execute print @.sql
no need to send parameter individually
u can add parameter within the sql statement 

|||

i tried that. I'll try agian theyere might be something i missed but i dont think so.

I have tired eveything and have figured out that it cant be done. Sanson