Powershell sql query connection remote forest
i need to make connection to the sql server which is in different forest for which i have creds how do i make connection to remote sql server and query the database
(remote sql server = sql24567-000.outerspace.net)
$SQLServer = 'SQL87630004-002.innerspace.net';
$Database = 'origindb';
$SqlQuery = @'
SELECT TOP 1000 [SecretId]
,[SecretName]
,[SecretType]
,[SecretKey]
,[FarmId]
,[State]
,[Scope]
,[ObjectId]
,[Version]
,[CreationTime]
,[WinAuth]
FROM [origindb].[dbo]
where Name like '%spo%'
## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = `
"Server = $SQLServer; Database = $Database; Integrated Security = True";
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;
## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
$DataSetTable
i found the answer i used invoke command to query the sl server
$session = New-PSSession -ComputerName sql24567-000.outerspace.net -Credential "innerspace\ajmaur"
Invoke-command -Session $session -ScriptBlock
$SQLServer = 'sql24567-000.outerspace.net';
$Database = 'origindb';
$SqlQuery = @'
SELECT TOP 1000 [SecretId]
,[SecretName]
,[SecretType]
,[SecretKey]
,[FarmId]
,[State]
,[Scope]
,[ObjectId]
,[Version]
,[CreationTime]
,[WinAuth]
FROM [origin].[dbo]
where Name like '%spo%'
## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = `
"Server = $SQLServer; Database = $Database; Integrated Security = True";
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;
## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
$DataSetTable
Similar Messages
-
Select type_address in Portal report's sql query using remote database
how do i select type_address item from remote database table ?
I've already create the database link called db_link.
I've already execute the sql statement in the specified database, and it works.
for example: ( sql plus in the specified database )
select syk.alamat_syarikat.alamat1 from MCS_SYARIKAT syk
for example: ( sql statement in portal report using database link )
select nama_syarikat, syk.alamat_syarikat.alamat1 from MCS_SYARIKAT@dblink syk
error massage:
Unable to describe SQL statement. Please correct it (WWV-13010)
Invalid SQL statement: select syk.alamat_syarikat.alamat1 from MCS_SYARIKAT@dblink syk (WWV-13005)
ORA-01001: invalid cursor (WWV-11230)
ORA-22804: remote operations not permitted on object tables or user-defined type columns (WWV-11230)
Failed to parse as MCS_PUBLIC - select syk.alamat_syarikat.alamat1 from MCS_SYARIKAT@dblink syk (WWV-08300)Here's the actual query:
SELECT BUILD_EXT_RES_LIST(EXT_FILE.ID) A
FROM EXT_FILE_RES, EXT_FILE
WHERE EXT_FILE_RES.ON_OWNER_PROFILE = 'Y' AND
EXT_FILE.OWNER_ID = :PROFILE AND
EXT_FILE.ID = EXT_FILE_RES.EXT_ID AND
(RES_SUBSCRIBER_YN(EXT_FILE.ID,:CURR_ID) = 'YES' OR
ADMINYESNO(:CURR_ID,:PROFILE) = 'YES')
ORDER BY EXT_FILE.FILE_NAMEAnd here's the actual error message:
1 error has occurred
Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing. ORA-00904: "SER_IS_ADMINYESNO": invalid identifier -
SQL Plus Connect remotely as SYSDBA
Hi
I am using Oracle XE on Ubuntu. On the database server I connect to Sys using following
sqlplus "/as sysdba"It works fine.
Now I want to use my remote machine to connect to the same database. I tried the following but it does not work.
sqlplus "sys/password@serverIP as sysdba"
ERROR:
ORA-01031: insufficient privilegesPlease help me to connect to my database remotely with sys user as sysdba.
Thanks
HabibHi OP,
If you want to connect to the database remotely (over network) as a SYSDBA, you need to make sure following two things are met:
1.Set the database parameter REMOTE_LOGIN_PASSWORDFILE = { shared | exclusive | none }
IT SHOULD BE SET TO shared/exclusive, IN ORDER FOR DATABASE TO ALLOW REMOTE CONNECTION
Now you check this parameter value in your database, if it is not set to shared/exclusive, set it first.
2. Check the password file (as suggested above) at location $ORACLE_HOME/dbs/, which is being used for authentication when users login to the database as a sysdba. If password file does exit then create a new one (as suggested) and set the password.
Now try connecting to the database remotely, still error paste the complete error message..
HTH
Edited by: pgoel on Mar 10, 2011 9:29 AM -
SQL query in powershell Errors on IIF
Hello,
I have put together a Powershell script from examples online to run a SQL query. The query came from Access and it seems Powershell has a problem with the syntax.
I'm pretty new to scripting and adding SQL to the equation isn't helping.
Powershell code
$SQLServer = "ServerName"
$SQLDBName = "DataBase"
$SqlQuery = 'MyQuery'
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0] | ft -AutoSize
SQL Query
SELECT swName AS Server, swRack AS Rack, swEnvironment AS Environment, IIf([dbo.SW_SERVICE_LVL].[swMonday]=1,"Mon") AS [RebootSchedule], dbo.SW_SERVICE_LVL.swMonBeginTime AS [RebootTime], 2 AS Expr
FROM dbo.SW_SERVICE_LVL INNER JOIN dbo.SW_SPECIALTY ON dbo.SW_SERVICE_LVL.swDiscount = dbo.SW_SPECIALTY.swSpecialtyId
WHERE (((IIf([dbo.SW_SERVICE_LVL].[swMonday]=1,"Mon")) Is Not Null) AND ((dbo.SW_SERVICE_LVL.swGrpResp)="IT Group Name") AND ((dbo.SW_SERVICE_LVL.swRootObjectType)="Server"));
Error given is
Exception calling "Fill" with "1" argument(s): "Incorrect syntax near ')'.
Incorrect syntax near 'IIf'."At line:16 char:1
+ $SqlAdapter.Fill($DataSet)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlExceptionThis might be considered a new question but now I got the powershell code to return data from the SQL database.
Now I am looking to output the table to a powershell Array then append the LastRebootTime into that Array. As far as I can tell, this requires a ForEach loop on each servername returned from the SQL query. And I'm stuck on getting that working.
Stop thinking like you know what that means.
Where are you getting lastreboottime? Why does it have to be appended. "Reboottime" is one of thefields in or query. You don't need it.
¯\_(ツ)_/¯
That is a bit strongly worded. Here's what I've got and this is still a work in progress. I've said this before, I am not a scripter. Now I am stuck on adding the LastBootUpTime column into the table returned from the SQL query.
$SQLServer = "ServerName"
$SQLDBName = "DataBase"
$SqlQuery = 'MyQuery'
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) | Out-Null
$arraydata = @($DataSet)
$SqlConnection.Close()
$servers = @($DataSet.Tables[0]) | select -ExpandProperty Server
Try{
foreach ($server in $servers)
$arraydata += @(GWMI -ComputerName $server -Class Win32_OperatingSystem -ErrorAction SilentlyContinue | select @{LABEL="Server";Expression={$_."csname"}}, @{LABEL='LastBootUpTime'
;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}})
}#end try
Catch{
"Can't work with $server"
$DataSet.Tables[0] | ft -AutoSize #Export-Csv -NoTypeInformation -Path c:\sunday.csv
$arraydata -
Could not connect to SQL Server 2012 Remotely
Hello,
I have a situation as follows:
The Server
SQL Server 2012 Standard Edition installed on Windows Server 2012 Standard Edition
Active Directory is installed on the same server as well
Remote Access Role added and configured to connect VPN
DNS Role added
Windows Firewall is disabled
The Server is connected to the internet
SQL Server Service & SQL Browser both are running under domain accounts
SQL Server allows remote connections
The Router
The router that connects the server to the Internet is configured to:
Enable VPN Tunnels Protocols (PPTP, L2TP and IPSec)
Forwarding > Virtual Servers (all requests on TCP and UDP on all ports to the server local IP)
The Client
PC running Windows 7 SP1 with SQL Server 2012 Express
Joined AD on the server
Connected to the internet
VPN Connected to the Server
Can Remote Desktop the Server
Can ping the server host name
Can nslookup the server host name
The Problem
If Both the Server and the Client are connected in the same Local Area Network, Client can connect to the SQL Serve
Once the Client is placed in different location connected to the Interent, VPN connected as described above, I could not connect to the Server using:
Windows Authentication Domain Users or
SQL Server users
and the error message is:
Cannot connect to SERVER\SQLINSTANCE.
ADDITIONAL INFORMATION:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider:
SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=-1&LinkId=20476
Any thoughts
Thanks in advance
Hello Hilary,
I have been working on a small replication test.
On the Publisher, things went smooth and the Snapshot Agent was able to work and produce a snapshot written in a shared folder located on the Publisher
On the Subscriber, as I am testing from SQL Server Express, I had run the following command:
replmerg.exe -Publisher [SERVER\SQLInstance] -PublisherDB [dbRepl] -PublisherSecurityMode 0 -PublisherLogin rplMergeAgent -PublisherPassword p@ssw0rd -Publication [TEST Publication] -Distributor [SERVER\SQLInstance] -DistributorSecurityMode 0 -DistributorLogin
rplMergeAgent -DistributorPassword p@ssw0rd -Subscriber [SUBSCRIBER\SQLInstance] -SubscriberSecurityMode 0 -SubscriberLogin rplMergeAgent -SubscriberPassword p@ssw0rd -SubscriberDB [dbRepl] -SubscriptionType 1 -OutputVerboseLevel 2 -Output C:\TEMP\mergeagent.log
Where
SERVER
Publisher and Distributor
dbRepl
Database to replicate
Merge Agent
rplMergeAgent
Subscriber
SUBSCRIBER
dbRepl
Subscriber Database
Merge Agent
rplMergeAgent
Password
p@ssw0rd
rplMergeAgent
SQL Login defined in both Publisher and Subscriber with same password
Granted the following at Publisher:
Login to Publication Database (dbRepl)
Login to Distribution Database (distribution)
Member of PAL
Granted the following at Subscriber:
db_owner fixed database role in Subscription database (dbRepl)
I couldn't grant rplMergeAgent Read Permission on SnapshotFolder as it is only a SQL Login.
When I ran the above command line, I received the following error:
Message: The schema script 'Person_2.sch' could not be propagated to the subscriber.
I am pasting below the whole log file written by the above command:
2014-04-11 15:38:07.205 Microsoft SQL Server Merge Agent 11.0.2218.0
2014-04-11 15:38:07.342 Copyright (c) 2008 Microsoft Corporation
2014-04-11 15:38:07.389
2014-04-11 15:38:07.406 The timestamps prepended to the output lines are expressed in terms of UTC time.
2014-04-11 15:38:07.433 User-specified agent parameter values:
-Publisher SERVER\SQLInstance
-PublisherDB dbRepl
-PublisherSecurityMode 0
-PublisherLogin rplMergeAgent
-PublisherPassword **********
-Publication TEST Publication
-Distributor SERVER\SQLInstance
-DistributorSecurityMode 0
-DistributorLogin rplMergeAgent
-DistributorPassword **********
-Subscriber SUBSCRIBER\SQLInstance
-SubscriberSecurityMode 0
-SubscriberLogin rplMergeAgent
-SubscriberPassword **********
-SubscriberDB dbRepl
-SubscriptionType 1
-OutputVerboseLevel 2
-Output C:\TEMP\mergeagent.log
2014-04-11 15:38:07.497 Percent Complete: 0
2014-04-11 15:38:07.517 Connecting to Subscriber 'SUBSCRIBER\SQLInstance'
2014-04-11 15:38:07.518 Connecting to OLE DB Subscriber at datasource: 'SUBSCRIBER\SQLInstance', location: '', catalog: 'dbRepl', providerstring: '' using provider 'SQLNCLI11'
2014-04-11 15:38:07.608 OLE DB Subscriber: SUBSCRIBER\SQLInstance
DBMS: Microsoft SQL Server
Version: 10.50.4000
catalog name: dbRepl
user name: rplMergeAgent
API conformance: 0
SQL conformance: 0
transaction capable: 1
read only: F
identifier quote char: "
non_nullable_columns: 0
owner usage: 15
max table name len: 128
max column name len: 128
need long data len:
max columns in table: 1000
max columns in index: 16
max char literal len: 131072
max statement len: 131072
max row size: 131072
2014-04-11 15:38:07.613 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': select SERVERPROPERTY ('ProductVersion')
2014-04-11 15:38:07.617 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': set nocount on declare @dbname sysname select @dbname = db_name() declare @collation nvarchar(255) select @collation = convert(nvarchar(255), databasepropertyex(@dbname, N'COLLATION')) select
collationproperty(@collation, N'CODEPAGE') as 'CodePage', collationproperty(@collation, N'LCID') as 'LCID', collationproperty(@collation, N'COMPARISONSTYLE') as 'ComparisonStyle',cast(case when convert (int,databasepropertyex (@dbname,'comparisonstyle')) &
0x1 = 0x1 then 0 else 1 end as bit) as DB_CaseSensitive,cast(case when convert (int,serverproperty ('comparisonstyle')) & 0x1 = 0x1 then 0 else 1 end as bit) as Server_CaseSensitive set nocount off
2014-04-11 15:38:07.637 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {?=call sp_helpsubscription_properties (N'SERVER\SQLInstance', N'dbRepl', N'TEST Publication')}
2014-04-11 15:38:07.681 Distributor security mode: 0, login name: rplMergeAgent, password: ********.
2014-04-11 15:38:07.682 Percent Complete: 0
2014-04-11 15:38:07.683 Connecting to Distributor 'SERVER\SQLInstance'
2014-04-11 15:38:07.684 Connecting to OLE DB Distributor at datasource: 'SERVER\SQLInstance', location: '', catalog: '', providerstring: '' using provider 'SQLNCLI11'
2014-04-11 15:38:25.062 OLE DB Distributor: SERVER\SQLInstance
DBMS: Microsoft SQL Server
Version: 11.00.2100
catalog name:
user name: guest
API conformance: 0
SQL conformance: 0
transaction capable: 1
read only: F
identifier quote char: "
non_nullable_columns: 0
owner usage: 15
max table name len: 128
max column name len: 128
need long data len:
max columns in table: 1000
max columns in index: 16
max char literal len: 131072
max statement len: 131072
max row size: 131072
2014-04-11 15:38:28.887 OLE DB Distributor 'SERVER\SQLInstance': select SERVERPROPERTY ('ProductVersion')
2014-04-11 15:38:29.842 OLE DB Distributor 'SERVER\SQLInstance': {call sp_helpdistpublisher (N'SERVER\SQLInstance') }
2014-04-11 15:38:32.198 OLE DB Distributor 'SERVER\SQLInstance': select datasource, srvid from master..sysservers where upper(srvname) = upper(N'SERVER\SQLInstance')
2014-04-11 15:38:33.199 OLE DB Distributor 'SERVER\SQLInstance': {call sp_MShelp_merge_agentid (0,N'dbRepl',N'TEST Publication',null,N'dbRepl',100,N'SUBSCRIBER\SQLInstance')}
2014-04-11 15:38:34.451 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:38:34.560 OLE DB Distributor 'SERVER\SQLInstance': {call sp_MShelp_profile (23, 4, N'')}
2014-04-11 15:38:36.189 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:38:36.499 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_get_redirected_publisher(N'SERVER\SQLInstance',N'dbRepl',0)}
2014-04-11 15:38:37.396 Percent Complete: 0
2014-04-11 15:38:37.396 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:38:37.399 Initializing
2014-04-11 15:38:37.401 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:38:37.403 Connecting to OLE DB Publisher at datasource: 'SERVER\SQLInstance', location: '', catalog: 'dbRepl', providerstring: '' using provider 'SQLNCLI11'
2014-04-11 15:38:38.427 Percent Complete: 0
2014-04-11 15:38:38.428 Validating publisher
2014-04-11 15:38:38.429 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:38:39.455 Percent Complete: 0
2014-04-11 15:38:39.456 Connecting to Publisher 'SERVER\SQLInstance'
2014-04-11 15:38:39.457 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:38:46.548 OLE DB Publisher: SERVER\SQLInstance
DBMS: Microsoft SQL Server
Version: 11.00.2100
catalog name: dbRepl
user name: rplMergeAgent
API conformance: 0
SQL conformance: 0
transaction capable: 1
read only: F
identifier quote char: "
non_nullable_columns: 0
owner usage: 15
max table name len: 128
max column name len: 128
need long data len:
max columns in table: 1000
max columns in index: 16
max char literal len: 131072
max statement len: 131072
max row size: 131072
2014-04-11 15:38:50.282 OLE DB Publisher 'SERVER\SQLInstance': set nocount on declare @dbname sysname select @dbname = db_name() declare @collation nvarchar(255) select @collation = convert(nvarchar(255), databasepropertyex(@dbname, N'COLLATION')) select collationproperty(@collation,
N'CODEPAGE') as 'CodePage', collationproperty(@collation, N'LCID') as 'LCID', collationproperty(@collation, N'COMPARISONSTYLE') as 'ComparisonStyle',cast(case when convert (int,databasepropertyex (@dbname,'comparisonstyle')) & 0x1 = 0x1 then 0 else 1 end
as bit) as DB_CaseSensitive,cast(case when convert (int,serverproperty ('comparisonstyle')) & 0x1 = 0x1 then 0 else 1 end as bit) as Server_CaseSensitive set nocount off
2014-04-11 15:38:57.393 OLE DB Publisher 'SERVER\SQLInstance': select SERVERPROPERTY ('ProductVersion')
2014-04-11 15:38:59.236 Connecting to OLE DB Publisher at datasource: 'SERVER\SQLInstance', location: '', catalog: 'dbRepl', providerstring: '' using provider 'SQLNCLI11'
2014-04-11 15:39:07.271 OLE DB Publisher: SERVER\SQLInstance
DBMS: Microsoft SQL Server
Version: 11.00.2100
catalog name: dbRepl
user name: rplMergeAgent
API conformance: 0
SQL conformance: 0
transaction capable: 1
read only: F
identifier quote char: "
non_nullable_columns: 0
owner usage: 15
max table name len: 128
max column name len: 128
need long data len:
max columns in table: 1000
max columns in index: 16
max char literal len: 131072
max statement len: 131072
max row size: 131072
2014-04-11 15:39:45.229 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:39:45.234 Percent Complete: 0
2014-04-11 15:39:45.235 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:39:45.236 Retrieving publication information
2014-04-11 15:39:45.238 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:39:46.287 Percent Complete: 0
2014-04-11 15:39:46.288 Retrieving subscription information.
2014-04-11 15:39:46.290 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:40:00.472 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:40:00.478 Percent Complete: 0
2014-04-11 15:40:00.479 Applying the snapshot to the Subscriber
2014-04-11 15:40:00.480 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:40:02.535 OLE DB Distributor 'SERVER\SQLInstance': select datasource, srvid from master..sysservers where upper(srvname) = upper(N'SERVER\SQLInstance')
2014-04-11 15:40:03.559 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_mergesubentry_indistdb (0,N'SERVER\SQLInstance',N'dbRepl',N'TEST Publication',N'SUBSCRIBER\SQLInstance',N'dbRepl',1,1,0,N'',?,90)}
2014-04-11 15:40:04.600 Connecting to OLE DB Subscriber at datasource: 'SUBSCRIBER\SQLInstance', location: '', catalog: 'dbRepl', providerstring: '' using provider 'SQLNCLI11'
2014-04-11 15:40:04.609 OLE DB Subscriber: SUBSCRIBER\SQLInstance
DBMS: Microsoft SQL Server
Version: 10.50.4000
catalog name: dbRepl
user name: rplMergeAgent
API conformance: 0
SQL conformance: 0
transaction capable: 1
read only: F
identifier quote char: "
non_nullable_columns: 0
owner usage: 15
max table name len: 128
max column name len: 128
need long data len:
max columns in table: 1000
max columns in index: 16
max char literal len: 131072
max statement len: 131072
max row size: 131072
2014-04-11 15:40:04.611 OLE DB Subscriber: SUBSCRIBER\SQLInstance
DBMS: Microsoft SQL Server
Version: 10.50.4000
catalog name: dbRepl
user name: rplMergeAgent
API conformance: 0
SQL conformance: 0
transaction capable: 1
read only: F
identifier quote char: "
non_nullable_columns: 0
owner usage: 15
max table name len: 128
max column name len: 128
need long data len:
max columns in table: 1000
max columns in index: 16
max char literal len: 131072
max statement len: 131072
max row size: 131072
2014-04-11 15:40:07.454 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': sp_MSacquiresnapshotdeliverysessionlock
2014-04-11 15:40:07.526 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': sp_MStrypurgingoldsnapshotdeliveryprogress
2014-04-11 15:40:07.530 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': sp_MSissnapshotitemapplied @snapshot_session_token = N'\\SERVER\Snapshot\unc\SERVER$SQLInstance_DBREPL_TEST PUBLICATION\20140411082109\', @snapshot_progress_token = N'\\SERVER\Snapshot\unc\SERVER$SQLInstance_DBREPL_TEST
PUBLICATION\20140411082109\Person_2.sch'
2014-04-11 15:40:24.659 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': sp_MSreleasesnapshotdeliverysessionlock
2014-04-11 15:40:24.663 The schema script 'Person_2.sch' could not be propagated to the subscriber.
2014-04-11 15:40:24.665 OLE DB Subscriber 'SUBSCRIBER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:40:24.690 Percent Complete: 18
2014-04-11 15:40:24.692 The schema script 'Person_2.sch' could not be propagated to the subscriber.
2014-04-11 15:40:24.693 OLE DB Distributor 'SERVER\SQLInstance': {call sys.sp_MSadd_merge_history90 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}
2014-04-11 15:40:27.541 Percent Complete: 0
2014-04-11 15:40:27.542 Category:NULL
Source: Merge Replication Provider
Number: -2147201001
Message: The schema script 'Person_2.sch' could not be propagated to the subscriber.
2014-04-11 15:40:28.563 Percent Complete: 0
2014-04-11 15:40:28.565 Category:AGENT
Source: SUBSCRIBER\SQLInstance
Number: 0
Message: The process could not read file '\\SERVER\Snapshot\unc\SERVER$SQLInstance_DBREPL_TEST PUBLICATION\20140411082109\Person_2.sch' due to OS error 1326.
2014-04-11 15:40:28.566 Disconnecting from OLE DB Subscriber 'SUBSCRIBER\SQLInstance'
2014-04-11 15:40:28.568 Disconnecting from OLE DB Subscriber 'SUBSCRIBER\SQLInstance'
2014-04-11 15:40:28.569 Disconnecting from OLE DB Subscriber 'SUBSCRIBER\SQLInstance'
2014-04-11 15:40:28.570 Disconnecting from OLE DB Subscriber 'SUBSCRIBER\SQLInstance'
2014-04-11 15:40:28.571 Disconnecting from OLE DB Publisher 'SERVER\SQLInstance'
2014-04-11 15:40:28.573 Disconnecting from OLE DB Publisher 'SERVER\SQLInstance'
2014-04-11 15:40:28.575 Disconnecting from OLE DB Publisher 'SERVER\SQLInstance'
2014-04-11 15:40:28.577 Disconnecting from OLE DB Publisher 'SERVER\SQLInstance'
2014-04-11 15:40:28.578 Disconnecting from OLE DB Distributor 'SERVER\SQLInstance'
2014-04-11 15:40:28.579 Disconnecting from OLE DB Distributor 'SERVER\SQLInstance'
I can say it is about how can the rplMergeAgent read the Shared folder.
What do you think? -
Email SQL query results from powershell
I currently have a script that I run every half hour which runs an sql query, and takes the results, and emails them to a group of users. The script states how many faxes are in a faxmaker queue. Now, the powers that be would like to add additional
information, and I wanted to know how to include the additional information in my query. So, here is the script that is working. I've changed some information to protect the innocent.
$DATETIME = Get-Date -Format "MM-dd-yyyy [HH:mm:ss]";
##### CREATE A LOG FILE AND INSERT A LOG HEADING ;
$LOG_HEADING = "SHOW FLORIDA INBOUND FAX QUEUES RAN @: " + $DATETIME ;
Add-Content "E:\psh\LiveScripts\logs\SHOW-FLORIDA-INBOUND-FAX-QUEUE.TXT" $LOG_HEADING ;
# get sql dbname sample
#email variables
$EmailFrom = "[email protected]" ;
$EmailTo = "My Email List"
$SqlServer = "MY-SQL-SERVER"
$SqlCatalog = "FAXmakerArchive"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT count (DISTINCT fax.ID) DATONA_BEACH_FAX_COUNT FROM
FM_FAXIN fax WITH (NOLOCK) LEFT OUTER JOIN T_FAX_REVIEW rvw WITH (NOLOCK) ON fax.ID = rvw.IDN_FAX WHERE (fax.RESULT LIKE '%SUCCESS%' OR (fax.RESULT NOT LIKE '%SUCCESS%' AND ATTACH_COUNT > 0)) AND
ISNULL(rvw.BOOL_IS_COMPLETE, 0) = 0 AND fax.LINE IN (SELECT LINE FROM T_LOCATION_FAX_LINE lne WITH (NOLOCK) WHERE lne.CDE_ACTIVE_FLAG = 1 AND lne.IDN_LOCATION =
3) AND fax.DATE > '2013-09-25' "
$SqlCmd.Connection = $SqlConnection
$NumberOfFlaInboundFaxes = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
if( $NumberOfFlaInboundFaxes -gt 29)
#Email Body
$EmailBody = @"
There are currently $NumberOfFlaInboundFaxes Faxes in the Florida Inbound Fax Queue ( )`n
Please Log in and help clear the Queue. Thank you. `n
`n`n`n
The people who recieved this email are: $EmailTo`n`n`n
From ApexAdmin/SystemScheduler
$EmailSubject = "There are " + $NumberOfFlaInboundFaxes + " faxes in the Inbound Florida Fax Queue. " + $DATETIME ;
#End of Email Body
#send mail via gmail through powersehll
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("email user", "email password");
$SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject , $EmailBody)
Else
Write-Host "NO ALERT on $DATETIME `n" -foreground 'DARKGREEN' -background 'WHITE' ;
#Write-output "There are currently: " $NumberOfFlaInboundFaxes " Faxes in the Florida Fax Queue"
Write-Host "There are currently " $NumberOfFlaInboundFaxes " Files in the Florida fax queue" -foreground 'DarkBLUE' -background 'white'
Write-Host "SMTP Alert sent to " ( "$EmailTo" ).ToUpper() " on $DATETIME `n" -foreground 'DARKBLUE' -background 'WHITE' ;
write-Host "WROTE AN ENTRY TO THE LOGFILE.`n" -foreground 'DARKGREEN' -background 'WHITE'
Now, I'd like to also include this query... also changed information to protect the innocent.
SELECT u.IDN_USER,
u.NAM_LASDBUSER,
u.NAM_FIRSDBUSER,
r.NAM_ROLE,
COUNT(o.IDN_ORDER) ORDER_CNT,
COUNT(DISTINCT
o.IDN_CLIENT) CLIENDBCNT,
(SELECT IDN_ZONE FROM DBUSER_PREF p WHERE u.IDN_USER = p.IDN_USER) IDN_USER_ZONE
FROM DBORDER o WITH (NOLOCK)
INNER JOIN DBUSER u WITH (NOLOCK)
ON o.IDN_USER_CRTD = u.IDN_USER
INNER JOIN DBROLE r WITH (NOLOCK)
ON u.IDN_ROLE = r.IDN_ROLE
WHERE DATEDIFF(d, GETDATE(), o.DTE_RECORD_CRTD)>=0 AND DATEDIFF(d, GETDATE(), o.DTE_RECORD_CRTD)<=0
AND r.IS_INTERNAL_USER = 1
GROUP BY u.IDN_USER, u.NAM_LASDBUSER, u.NAM_FIRSDBUSER, r.NAM_ROLE, r.IS_INTERNAL_USER
ORDER BY u.NAM_LASDBUSER, u.NAM_FIRSDBUSER
Thank you in advance for any suggestions, links, etc, you can provide. I don't mind doing the heavy lifting, ie: research and reading, just needed to be pointed in the right directions.
JohnAs an example this is more readable but could be improved which would make your adding a section much easier.
$DATETIME = Get-Date -Format 'MM-dd-yyyy [HH:mm:ss]'
$LOG_HEADING = "SHOW FLORIDA INBOUND FAX QUEUES RAN @: " + $DATETIME;
Add-Content "E:\psh\LiveScripts\logs\SHOW-FLORIDA-INBOUND-FAX-QUEUE.TXT" $LOG_HEADING;
$sql = @'
SELECT count(DISTINCT fax.ID) DATONA_BEACH_FAX_COUNT
FROM FM_FAXIN fax WITH (NOLOCK)
LEFT OUTER JOIN T_FAX_REVIEW rvw WITH (NOLOCK) ON fax.ID = rvw.IDN_FAX
WHERE
fax.RESULT LIKE '%SUCCESS%' OR (
fax.RESULT NOT LIKE '%SUCCESS%' AND ATTACH_COUNT > 0
AND ISNULL(rvw.BOOL_IS_COMPLETE, 0) = 0
AND fax.LINE IN (SELECT LINE FROM T_LOCATION_FAX_LINE lne WITH (NOLOCK)
WHERE lne.CDE_ACTIVE_FLAG = 1 AND lne.IDN_LOCATION = 3) AND fax.DATE > '2013-09-25'
$template=@'
There are currently {0} Faxes in the Florida Inbound Fax Queue ( )
Please Log in and help clear the Queue. Thank you.
The people who recieved this email are: $EmailTo
From ApexAdmin/SystemScheduler
$subject= 'There are {0} faxes in the Inbound Florida Fax Queue. {1:MM-dd-yyyy [HH:mm:ss]}'
$EmailFrom='[email protected]'
$EmailTo = "My Email List"
$SqlServer = "MY-SQL-SERVER"
$SqlCatalog = "FAXmakerArchive"
#run query
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $sql
$SqlCmd.Connection = $SqlConnection
$NumberOfFlaInboundFaxes = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
# build email if needed
if($NumberOfFlaInboundFaxes -gt 29){
$EmailBody=$template -f $NumberOfFlaInboundFaxes
$EmailSubject = $subject -f $NumberOfFlaInboundFaxes,[DateTime]::Now
$SMTPServer='smtp.gmail.com"'
$SMTPClient=New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("email user", "email password");
$SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject , $EmailBody)
}else{
Write-Host "NO ALERT on $DATETIME `n" -foreground 'DARKGREEN' -background 'WHITE' ;
Write-Host "There are currently $NumberOfFlaInboundFaxes Files in the Florida fax queue" -foreground 'DarkBLUE' -background 'white'
Write-Host "SMTP Alert sent to $EmailTo on $DATETIME" -foreground 'DARKBLUE' -background 'WHITE' ;
write-Host 'WROTE AN ENTRY TO THE LOGFILE.' -foreground 'DARKGREEN' -background 'WHITE'
\_(ツ)_/ -
MS SQL Server 2005 Remote Database Connection
Hello Friends,
I have a database in SQL Server 2005, i installed SQL server with windows authentication. Now when I tries to connect to the server using Type 3 jdbc. I downloaded jdbc 1.2 driver from,
http://msdn2.microsoft.com/hi-in/data/aa937724(en-us).aspx
now i want to connect to the database from remote machine(different network).
How can i achieve this, and what setting i have to make to the sql server?
Any suggestion will be greatly appreciated.
Regards
Mohneeshokey i done with some experiment.
now i am able to do it from local machine with the following code
String url="jdbc:sqlserver://LocalIP:1433;integratedSecurity=true;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("url");
now when i move to remote system and change the Local IP to remote IP(server has static IP)
it comes up with SQLException: Login failed.for user ''.
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. The user is not associated with a trusted SQL Server connection.
please help me its kinda urgent.
Regards
Mohneesh -
Query on SQL Developer Connections Tree Does Not Display Objects
Hi Gurus, Could you please clarify on the below. As per the note ID 1458753.1, SQL Developer Connections Tree Does Not Display Objects to user in order to access database objects outside the owned schema/account. ------------------------- By default, and without granting wide privileges such as DBA, a user will only see his or her own objects in the first level object nodes under their connection. Objects in other schemas must be accessed via the Other Users node under the connection. This is the intended functionality/display in SQL Developer. ------------------------- Is there any other way we can achieve this? Requirement is very common - user A owns all objects and user B granted read/read-write privileges on user A objects. Now user B wants to Display user A objects in the corresponding objects node of SQL developer. Could any one shed some light here? Thanks Venu
First off, there is a dedicated SQL Developer forum where lots of the developers hang out. Those folks are way more knowledgable that we are about the tool.
That said, I have no problem displaying dates. Do you just have a problem with this particular query/ field/ table? Or does it affect all dates? What version of SQL Developer are you using? 1.1 is out now.
Justin -
Java.sql.SQLException: Connection to remote site no longer valid
Hi
Somebody can help me with this ?
java.sql.SQLException: Connection to remote site no longer valid
Sometimes this error message appears in the moment when the next code execute, the database is Informix 10
public BeanOutParametersSMS siantelSMS(BeanArgumentsSMS bean)
throws SQLException, NumberFormatException,
NullPointerException, Exception {
String sql = "execute procedure SP_SMS_MKT(?,?,?,?,?,?,?,?,?)";
CallableStatement cs = null;
ResultSet rs = null;
BeanOutParametersSMS out = new BeanOutParametersSMS();
String salesForce = "";
try {
cs = connection.prepareCall(sql);
s.setString(1, bean.getAction());
cs.setString(2, "R0" + bean.getRegion());
cs.setString(3,bean.getCveclientesms());
cs.setString(4,bean.getPuerto());
cs.setString(5,bean.getCveproducto());
if (cs.execute()) {
rs = cs.getResultSet();
if (rs.next()) {
out.setActionInvoked(rs.getString(1));
out.setCode(rs.getString(2));
out.setPuerto(rs.getString(3));
out.setCveproducto(rs.getString(4)); etc ....
note. The stored procedure connecting with two databases (informix 10 & informix 9)Where do you close the connection and statement/result set?
-
With Multi-Factor Authentication ENABLED how can office 365 admin connect remotely to manage Office 365 with Power-Shell ?
When I key-in my credentials, auth fails with invalid username and password ?
Does any know the procedure ?This question was closed over a year ago. You will need to start a new question. You can post a link back here if you think it helps.
I also recommend asking in the O365 developers forum for how to do bulk license upgrades. You can use the answer here and just remove and then add the new license.
¯\_(ツ)_/¯ -
Morning all,
I've just been assigned a report-related project but I have not created much of anything in C# or .Net before!
I was wondering if someone could help me get started. Here are the specifications:
Basically, I am to create an automated report application. I have the query and I will include it further down
in this post. The page is to have a couple blanks to specify the Start Date and End Date and replace those dates in the query, and generate the report. What I need some help on is how to make the SQL query work in the application which I will connect to the
intended database to generate the report (basic I know, but I'm new at this) on Visual Studio 2010. I also need some help on programming the Start Date blank and End Date blank so that what the user types in for those blanks will replace the date fields in
the SQL query, then generate the report with the new dates.
I appreciate the help!
The SQL query and what the dates are replacing:
select
PTH.INST_ID ,
PTH.EMPLOYEE_ID,
DBH.HR_DEDUCTION_AND_BENEFITS_CODE,
replace(DB.DESCRIPTION,',',''),
DB.WITHHOLDING_LIABILITY_ACCOUNT_MASK,
DBH.HR_DEDUCTION_AND_BENEFITS_ID,
DBH.CHECK_DATE,
DBH.CHECK_NO,
DBH.FIN_INST_ACCT_ID,
replace(replace (DBH.COMMENT,CHAR(10),' '),CHAR(13),' '),
DBH.HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE,
DBH.LENGTH,
DBH.EMPLOYEE_COMPUTED_AMOUNT,
DBH.EMPLOYEE_BANK_ROUTING_NUMBER,
DBH.EMPLOYEE_ACCOUNT_TYPE,
DBH.EMPLOYEE_ACCOUNT_NUMBER,
DBH.EMPLOYER_COMPUTED_AMOUNT,
DBH.EMPLOYEE_GROSS_AMOUNT,
DBH.EMPLOYER_GROSS_AMOUNT,
DBH.PAYROLL_EXCLUDE,
PTH.VOID_DATE,
PTH.BATCH_QUEUE_ID,
B.BATCH_CODE,
BQ.FY,
BQ.END_DATE,
BQ.COMMENTS,
BQ.BATCH_CRITERIA_USED,
BP.COLUMN_VALUE,
PTH.REPLACEMENT,
P.LAST_NAME,
P.FIRST_NAME,
P.MIDDLE_NAME
from PY_EMPLOYEE_TAX_HISTORY PTH
INNER JOIN PERSON_EMPLOYEE PE ON
PE.INST_ID=PTH.INST_ID AND
PE.EMPLOYEE_ID=PTH.EMPLOYEE_ID
INNER JOIN PERSON P ON
PE.INST_ID=P.INST_ID AND
PE.PERSON_ID=P.PERSON_ID
LEFT JOIN HR_EMPLOYEE_DEDUCTIONS_AND_BENEFITS_HISTORY DBH ON
PTH.INST_ID=DBH.INST_ID AND
PTH.CHECK_DATE=DBH.CHECK_DATE AND
PTH.CHECK_NO=DBH.CHECK_NO AND
PTH.EMPLOYEE_ID=DBH.EMPLOYEE_ID
LEFT JOIN HR_DEDUCTION_AND_BENEFITS DB ON
DB.INST_ID=DBH.INST_ID AND
DB.HR_DEDUCTION_AND_BENEFITS_CODE=DBH.HR_DEDUCTION_AND_BENEFITS_CODE
LEFT JOIN BATCH_QUEUE BQ ON
PTH.BATCH_QUEUE_ID=BQ.BATCH_QUEUE_ID
LEFT JOIN BATCH B ON
B.BATCH_CODE=BQ.BATCH_CODE
LEFT JOIN BATCH_PARAMETER BP ON
BQ.BATCH_QUEUE_ID=BP.BATCH_QUEUE_ID
AND BP.COLUMN_NAME = 'SUPPRESS_DIRECT_DEPOSIT'
------Please change the WHERE condition for date range of the month you need to run this for.
WHERE PTH.CHECK_DATE >='07/01/2013'
AND PTH.CHECK_DATE <='07/31/2013'
and BQ.BATCH_CODE='BAT_PY_PAYCALC'
and bq.fy=2014
ORDER BY PTH.INST_ID ,
PTH.EMPLOYEE_ID,
DBH.HR_DEDUCTION_AND_BENEFITS_CODE,
DBH.CHECK_DATETry this code. The Server name will be the same name when you use SQL Server Management Studio (SSMS). It is in the login window for SSMS. I assume you are using SQLSTANDARD (not SQLEXPRESS) which is in the connection string in the code
below. I also assume you have remote connection allowed in the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
class Program
const string DATABASE = "Enter Database Name Here";
const string SERVER = "Enter Server Name Here";
static void Main(string[] args)
DateTime startDate = DateTime.Parse("07/01/2013");
string startDateStr = startDate.ToString("MM/dd/yyyy");
DateTime endDate = new DateTime(startDate.Year, startDate.Month + 1, 1).AddDays(-1);
string endDateStr = endDate.ToString("MM/dd/yyyy");
string connStr = string.Format("Server={0}\\SQLSTANDARD;Database={1};Trusted_Connection= True;", SERVER,DATABASE);
string SQL = string.Format(
"select\n" +
" PTH.INST_ID\n" +
",PTH.EMPLOYEE_ID\n" +
",DBH.HR_DEDUCTION_AND_BENEFITS_CODE,\n" +
",replace(DB.DESCRIPTION,',','')\n" +
",DB.WITHHOLDING_LIABILITY_ACCOUNT_MASK\n" +
",DBH.HR_DEDUCTION_AND_BENEFITS_ID\n" +
",DBH.CHECK_DATE\n" +
",DBH.CHECK_NO\n" +
",DBH.FIN_INST_ACCT_ID\n" +
",replace(replace (DBH.COMMENT,CHAR(10),' '),CHAR(13),' ')\n" +
",DBH.HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE\n" +
",DBH.LENGTH\n" +
",DBH.EMPLOYEE_COMPUTED_AMOUNT\n" +
",DBH.EMPLOYEE_BANK_ROUTING_NUMBER\n" +
",DBH.EMPLOYEE_ACCOUNT_TYPE\n" +
",DBH.EMPLOYEE_ACCOUNT_NUMBER\n" +
",DBH.EMPLOYER_COMPUTED_AMOUNT\n" +
",DBH.EMPLOYEE_GROSS_AMOUNT\n" +
",DBH.EMPLOYER_GROSS_AMOUNT\n" +
",DBH.PAYROLL_EXCLUDE\n" +
",PTH.VOID_DATE\n" +
",PTH.BATCH_QUEUE_ID\n" +
",B.BATCH_CODE\n" +
",BQ.FY\n" +
",BQ.END_DATE\n" +
",BQ.COMMENTS\n" +
",BQ.BATCH_CRITERIA_USED\n" +
",BP.COLUMN_VALUE\n" +
",PTH.REPLACEMENT\n" +
",P.LAST_NAME\n" +
",P.FIRST_NAME\n" +
",P.MIDDLE_NAME\n" +
" from PY_EMPLOYEE_TAX_HISTORY PTH\n" +
" INNER JOIN PERSON_EMPLOYEE PE ON\n" +
" PE.INST_ID=PTH.INST_ID AND\n" +
" PE.EMPLOYEE_ID=PTH.EMPLOYEE_ID\n" +
" INNER JOIN PERSON P ON\n" +
" PE.INST_ID=P.INST_ID AND\n" +
" PE.PERSON_ID=P.PERSON_ID\n" +
" LEFT JOIN HR_EMPLOYEE_DEDUCTIONS_AND_BENEFITS_HISTORY DBH ON\n" +
" PTH.INST_ID=DBH.INST_ID AND\n" +
" PTH.CHECK_DATE=DBH.CHECK_DATE AND\n" +
" PTH.CHECK_NO=DBH.CHECK_NO AND\n" +
" PTH.EMPLOYEE_ID=DBH.EMPLOYEE_ID\n" +
" LEFT JOIN HR_DEDUCTION_AND_BENEFITS DB ON\n" +
" DB.INST_ID=DBH.INST_ID AND\n" +
" DB.HR_DEDUCTION_AND_BENEFITS_CODE=DBH.HR_DEDUCTION_AND_BENEFITS_CODE\n" +
" LEFT JOIN BATCH_QUEUE BQ ON\n" +
" PTH.BATCH_QUEUE_ID=BQ.BATCH_QUEUE_ID\n" +
" LEFT JOIN BATCH B ON\n" +
" B.BATCH_CODE=BQ.BATCH_CODE\n" +
" LEFT JOIN BATCH_PARAMETER BP ON\n" +
" BQ.BATCH_QUEUE_ID=BP.BATCH_QUEUE_ID\n" +
" AND BP.COLUMN_NAME = 'SUPPRESS_DIRECT_DEPOSIT'\n" +
" WHERE PTH.CHECK_DATE >='{0}'\n" +
" AND PTH.CHECK_DATE <='{1}'\n" +
" and BQ.BATCH_CODE='BAT_PY_PAYCALC'\n" +
" and bq.fy=2014\n" +
" ORDER BY PTH.INST_ID\n" +
",PTH.EMPLOYEE_ID\n" +
",DBH.HR_DEDUCTION_AND_BENEFITS_CODE\n" +
",DBH.CHECK_DATE", startDateStr, endDateStr);
SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
DataTable dt = new DataTable();
adapter.Fill(dt);
jdweng
Could you elaborate more on what this code does in general?
Does it generate a table with the data between specified dates? If so, where is the table shown?
Where does one enter in the specified start and end dates on the Web Application? Do I have to create start and end date blanks and link them to the code for it to work?
Sorry for the inconvenience - I'm just really new at this. Thanks! -
Looking for a SQL query to get all the possible Alert Messages from the Rules in a Management Pack
For reporting, I'm looking to get a SQL query of all the possible Alert Messages for Rules configured in a Management Pack (not necessarily the ones that have thrown alerts). I can do this for Monitors, but not for Rules.
The configured alert messages for the Management Pack Monitors
go like this: ManagementPack > MonitorView> RuleModule > RuleModule.Alert Message > Localized Text
The configured alert messages for the Management Pack Rules
should go something like this, but there is a missing link: ManagementPack > RuleView > RuleModule > ? Missing Link ? > Localized Text
The Rules are tied to the Module, but I don't see a connection from the RulesModule to the Alert Message that I see in the LocalizedText. The Rule names do not always equal the Alert name.
Can someone provide the missing link?Hi,
please try below powershell code to find the corresponding management pack for specific alert:
$Alert = get-scomalert | where {$_.Name -like 'Agent Proxy Not Enabled*'} | select -first 1
If ($alert.IsMonitorAlert -eq "True") {
write-host "Ths is a monitor-generated alert"
get-scommonitor -ID $Alert.MonitoringRuleID | select Enabled, DisplayName, ManagementPack
else
write-host "This is a rule-generated alert"
get-scomrule -ID $Alert.MonitoringRuleID | select Enabled, DisplayName, ManagementPack
In addition, please also refer to the below link:
http://blogs.technet.com/b/mazenahmed/archive/2011/12/02/using-powershell-to-map-opsmgr-active-alert-to-its-corresponding-rule-monitor-and-management-pack-name.aspx
Regards,
Yan Li
Regards, Yan Li -
SQL Query results to CSV as two worksheets
I'm trying to take two SQL queries and get the results sent to a CSV file on two worksheets. Looking online I have not found a solid example of using the Excel ComObject to create a CSV then add a new worksheet to the CSV file. An added bonus
would be using AutoFit on the columns so everything is easily visible.
Code found online got me the following script which does work, however it takes 12 minutes to pipe the SQL queries to Excel. Switching to a CSV and the script executes in 5 seconds.
This is another nice to have, I was also looking the best way to look at the results (only 1 column) and depending on the length of the data, insert what Excel would call a Cell thereby shifting cells RIGHT but so far have found no clear examples of how
to accomplish that. My guess would be modifying my SQL queries but I've posted a question on StackOverFlow and someone suggested modifying the PowerShell Table created from the SQL dataset.Tables
Code:
$docs = "C:\Scripts\Output.xlsx"
If (Test-Path $docs){Remove-Item $docs}
Function Run-Query {
param([string[]]$queries,[string[]]$sheetnames)
## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application
$xlsObj.DisplayAlerts = $false
$xlsWb = $xlsobj.Workbooks.Add(1)
## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0
$time = 2
for ($i = 0; $i -lt $queries.Count; $i++){
$percentage = $i / $time
$remaining = New-TimeSpan -Seconds ($time - $i)
$message = "{0:p0} complete" -f $percentage, $remaining
Write-Progress -Activity "Creating Daily Reboot Spreadsheet" -status $message -PercentComplete ($percentage * 100)
$query = $queries[$i]
$sheetname = $sheetnames[$i]
$xlsSh = $xlsWb.Worksheets.Add([System.Reflection.Missing]::Value, $xlsWb.Worksheets.Item($xlsWb.Worksheets.Count))
$xlsSh.Name = $sheetname
### SQL query results sent to Excel
$SQLServer = 'ServerName'
$Database = 'DataBase'
## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $query
$SqlCmd.Connection = $SqlConnection
## - Extract and build the SQL data object '$Table2':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$Table1 = $DataSet.Tables["Table"]
## - Build the Excel column heading:
[Array] $getColumnNames = $Table1.Columns | SELECT ColumnName
## - Build column header:
[Int] $RowHeader = 1
foreach ($ColH in $getColumnNames)
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
$RowHeader++
## - Adding the data start in row 2 column 1:
[Int] $rowData = 2
[Int] $colData = 1
foreach ($rec in $Table1.Rows)
foreach ($Coln in $getColumnNames)
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@"
## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
$ColData++
$rowData++; $ColData = 1
## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange
[void] $xlsRng.EntireColumn.AutoFit()
}#End For loop.
#Delete unwanted Sheet1.
$xlsWb.Sheets.Item('Sheet1').Delete()
#Set Monday to Active Sheet upon opening Workbook.
$xlsWb.Sheets.Item('Cert').Activate()
## ---------- Saving file and Terminating Excel Application ---------- ##
$xlsFile = "C:\Scripts\Output.xlsx"
[void] $xlsObj.ActiveWorkbook.SaveAs($xlsFile)
$xlsObj.Quit()
## - End of Script - ##
start-sleep 2
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End Function
$queries = @()
$queries += "Query1"
$queries += "Query2"
$sheetnames = @('Cert','Prod')
Run-Query -queries $queries -sheetnames $sheetnamesHere's what I ended up with that accomplishes my goal. I learned it's not possible to create a CSV with two worksheets since Excel will allow this but the CSV cannot be saved with the second worksheet. Instead, I create two CSV files then merge
them into one Excel workbook, one CSV per worksheet. In my case, this happens in 5 seconds. There is one thing which must be mentioned, I've seen this script fail the first time it is run but will successfully run the second time.
Also note, after much trial and error, this code correctly cleans up the Excel ComObject!! -Thanks go to JRV.
$docs = "D:\Scripts\MonthlyReboots.xlsx"
IF (Test-Path $docs){Remove-Item $docs}
$csv1 = "D:\Scripts\Cert.csv"
IF (Test-Path $csv1){Remove-Item $csv1}
$csv2 = "D:\Scripts\Prod.csv"
IF (Test-Path $csv2){Remove-Item $csv2}
Function Run-Query {
param([string[]]$queries,[string[]]$sheetnames,[string[]]$filenames)
Begin{
$SQLServer = 'ServerName'
$Database = 'DataBase'
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = 0
$dest = $Excel.Workbooks.Add(1)
}#End Begin
Process{
For($i = 0; $i -lt $queries.Count; $i++){
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $queries[$i]
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "D:\Scripts\$($sheetnames[$i]).csv" -Force
}#end for loop.
}#End Process
End{
$SqlConnection.Close()
#Excel magic test!
For($i = 0; $i -lt $queries.Count; $i++){
$loopy = (Resolve-Path -Path $filenames[$i]).ProviderPath
$Book = $Excel.Workbooks.Open($loopy)
$next = $Excel.workbooks.Open($loopy)
$next.ActiveSheet.Move($dest.ActiveSheet)
$xlsRng = $dest.ActiveSheet.UsedRange
$xlsRng.EntireColumn.AutoFit() | Out-Null
$dest.sheets.item('Sheet1').Delete()
$xlsFile = "D:\Scripts\MonthlyReboots.xlsx"
[void] $Excel.ActiveWorkbook.SaveAs($xlsFile)
$Excel.Quit()
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($next)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Book)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End end block.
}#End function run-query.
$queries = @()
$queries += @'
Select * from table1
$queries += @'
Select * from table2
$sheetnames = @("Cert","Prod")
$filenames = @("D:\Scripts\Prod.csv","D:\Scripts\Cert.csv")
Run-Query -queries $queries -sheetnames $sheetnames -filenames $filenames
Start-Sleep -Milliseconds 50
Invoke-Item D:\Scripts\MonthlyReboots.xlsx -
SSRS Report Viewer 2012 Cancel Link on loading spinner not stopping SQL Query
Hi
I searched the forum for this one and didn't find anything germane, so here goes.
In SSRS 2012 when running a report interactively if you hit cancel it basically does nothing but stop the spinner and prevent the request from completing.
I'd like to kill the SQL Query (dataset refresh) when the Cancel link is pressed.
I recall seeing on article somewhere about doing a callback and calling some other method on the web service to kill the query, but I can't find it now.
Any help is much appreciated!
ThanksHi James,
In SQL Server Reporting Services, a job will be created by SQL Server Agent if any of the following processes is underway:
query execution on a remote or local database server
report processing
report rendering
To cancel a job that is running on the report server, we can cancel the job directly or reduce the report execution time-out value in the SQL Server Management Studio. Please refer to the steps below:
Open SQL Server Management Studio, and connect to "Reporting Services".
Under the Report Server node, right-click on the "Jobs" folder and select "Refresh". Then, right-click on "Jobs" again and click "Cancel All Jobs".
Right-click on the Report Server node and open the "Server Properties" dialog.
Click the "Execution" option, and set the "Limit report execution to the following number of seconds:" to a much smaller number. After this issue is resolved, this configuration should revert to the previous state.
Reference:
Managing a Running Process
Setting Time-out Values for Report and Shared Dataset Processing
In addition, we can also use the KILL Transact-SQL statement to terminate a normal connection by terminating the transactions that are associated with the specified session ID. For the details information, you can refer to:
KILL (Transact-SQL)
If you still have any problem, please feel free to ask.
Regards,
Vicky Liu
Vicky Liu
TechNet Community Support -
Does the local server send the query to remote server?
I have 2 servers,a local server connect with remote server through database link.If I execute a query at local server but only access tables in remote server,does local server send this query to remote server or all the tables at remote server will send to local server?If local server send this query to remote server,does it can execute another query while it waits the result send from remote server?
Any help would be appreciated
RegardsYes is executed on remote , and the remote can accept queries as normal see my example below
SQL> select * from v$database@prod_p;
Execution Plan
Plan hash value: 3039639316
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time
| Inst |
| 0 | SELECT STATEMENT REMOTE| | 100 | 64400 | 0 (0)| 00:00:0
1 | |
| 1 | MERGE JOIN CARTESIAN | | 100 | 64400 | 0 (0)| 00:00:0
1 | |
|* 2 | FIXED TABLE FULL | X$KCCDI | 1 | 582 | 0 (0)| 00:00:0
1 | RPRD |
| 3 | BUFFER SORT | | 100 | 6200 | 0 (0)| 00:00:0
1 | |
| 4 | FIXED TABLE FULL | X$KCCDI2 | 100 | 6200 | 0 (0)| 00:00:0
1 | RPRD |
Predicate Information (identified by operation id):
2 - filter("DI"."INST_ID"=USERENV('INSTANCE'))
Note
- fully remote statement
Maybe you are looking for
-
New Windows server 2003 Hyper-V guest fails to boot
Hello, I'm currently doing some virtualization experiments on my new server hardware. The host hardware is: IBM x3650 M4 x2 Xeon E5-2609 32GB RAM x2 480 GB SSDs Server OS: Windows server 2012 I'd like to test some legacy app virtualization. I've conf
-
How to use single ant build script to package the application with and without native extensions
Hi, I am using iOS native extensions for Adobe air. For this I am listing the extensions in the application descriptor file. Since the package with native extensions are meant to run only on device, I want my build script to work without native exten
-
How to Change the Font Color in the Podcast Archive Subheadings
If you go to pages.sparcc.org/The _Sanctuary, you will notice that the font colors in the subheadings are red. I was able to change them to the green everyone wanted except for the red "Archives". How can I change them?
-
Help,why brconnect do not collect statistics for mseg table?
I found "MSEG" table`s statistics is too old. so i check logs in db13,and the schedule job do not collect statistics for "MSEG". Then i execute manually: brconnect -c -u system/system -f stats -t mseg -p 4 this command still do not collect for mseg.
-
A bapi problem of create sales order
hello,experts, when I want to try the function of bapi 'BAPI_SALESORDER_CREATEFROMDAT1', the return message is the following, 'Material 4070111 is not defined for sales org.4050, distr.chan.01, language ZH',actually,the sales org.4050 is defined fo