Executing SQL powershell query in VBscript - sql

I am executing sql query in vbscript, query is as follow it gives information about drives available for each server
VBScript code (slightly restructured):
Strquery = "DECLARE #Totaldbspacegb BIGINT;" & _
"DECLARE #Totaldriveusedspacegb INT;" & _
"DECLARE #Totaldrivefreespacegb INT;" & _
"DECLARE #Svrname VARCHAR(255);" & _
"DECLARE #Sql VARCHAR(400);" & _
"DECLARE #Forcast6monthsgb NUMERIC(38, 6);" & _
"DECLARE #Forcast12monthsgb NUMERIC(38, 6);"
Strquery = Strquery & "; DECLARE #Avggrowthingb NUMERIC(38, 6);" & _
"CREATE TABLE #Temp1(Yer INT NULL, Mnth INT NULL," & _
"Sumdbinmb NUMERIC(38, 6)NULL, Id INT IDENTITY(1, 1) NOT NULL);" & _
"CREATE TABLE #Temp4(Totaldriveusedspacegb INT, Totaldrivefreespacegb INT);"
Strquery = Strquery & "; SELECT #Totaldbspacegb = SUM(Size) FROM Sys.Master_Files"
Strquery = Strquery & "; SELECT #Totaldbspacegb = #Totaldbspacegb * 8. / 1024.0 / 1024"
Strquery = Strquery & "; SET #Svrname = '" & Strserver & "';"
Sql = " Powershell.Exe - C ""Get-WmiObject -Class Win32_Volume -Filter ''DriveType = 3''| select name,label,capacity,freespace | foreach{$_.name+''!''+$_.label+''|''+$_.capacity/1048576+''%''+$_.freespace/1048576+''*''}"""
Strquery = Strquery & "CREATE TABLE #Output(Line VARCHAR(255)); INSERT INTO #Output"
Strquery = Strquery & "; EXEC Xp_Cmdshell '" & sql & "';"
Strquery = Strquery & "; SELECT * FROM #Output;"
Resulting (formatted) SQL code:
DECLARE #Totaldbspacegb BIGINT;
DECLARE #Totaldriveusedspacegb INT;
DECLARE #Totaldrivefreespacegb INT;
DECLARE #Svrname VARCHAR(255);
DECLARE #Sql VARCHAR(400);
DECLARE #Forcast6monthsgb NUMERIC(38, 6);
DECLARE #Forcast12monthsgb NUMERIC(38, 6);
;
DECLARE #Avggrowthingb NUMERIC(38, 6);
CREATE TABLE #Temp1(Yer INT NULL,
Mnth INT NULL,
Sumdbinmb NUMERIC(38, 6)NULL,
Id INT IDENTITY(1, 1) NOT NULL
);
CREATE TABLE #Temp4(Totaldriveusedspacegb INT,
Totaldrivefreespacegb INT
);
;
SELECT #Totaldbspacegb = SUM(Size)
FROM Sys.Master_Files;
SELECT #Totaldbspacegb = #Totaldbspacegb * 8. / 1024.0 / 1024;
SET #Svrname = '...';
CREATE TABLE #Output(Line VARCHAR(255));
INSERT INTO #Output;
EXEC Xp_Cmdshell 'Powershell.Exe - C "Get-WmiObject -Class Win32_Volume -Filter ''DriveType = 3''| select name,label,capacity,freespace | foreach{$_.name+''!''+$_.label+''|''+$_.capacity/1048576+''%''+$_.freespace/1048576+''*''}"';
;
SELECT *
FROM #Output;
I am executing this query it gave me output while running from management studio while running in .vbs file it give me record count as null, how to find whether query is executing sucessfully.
is it due to powershell command it is not running in vbscript.
Please help

Do you want to update the temporary table #Output with the result of the PowerShell command? If so, I don't think your instructions will do what you want.
INSERT INTO #Output;
EXEC Xp_Cmdshell 'Powershell.Exe -C "..."';
SELECT *
FROM #Output;
INSERT INTO #Output; is not a valid statement, and you don't do anything with the output of the PowerShell command.

Related

Unclosed quotation mark after the character string ')'

I have a stored procedure SP_CHADOTHERREPORTS
When executing SP_CHADOTHERREPORTS from VB.NET. I get an error like this:
here is my code for executing SP_CHADOTHERREPORTS in VB.NET:
Dim subreporttype as varchar = "Report1"
Dim DatabaseFINAL as varchar = "TBLREPORT"
Dim acctcode as varchar = "TBLREPORT.acctcode"
Dim varmonth as integer = 1
Dim varyear as integer = 2011
Execute("EXECUTE SP_CHADOTHERREPORTS '" & subreporttype & "','" & DatabaseFINAL & "','" & acctcode & "'," & dt.Rows(ctr).Item("ReporttypeName").ToString & "," & varmonth & ", " & varyear & "")
While this one is the code in SP_CHADOTHERREPORTS from SQL SERVER 2008:
ALTER PROCEDURE [dbo].[SP_CHADOTHERREPORTS]
#Subreport as varchar(100),
#TableName as varchar(100),
#AccountCode as varchar(100),
#ReportName as varchar(100),
#AcctPeriod as numeric(18,0),
#AcctYear as numeric(18,0)
AS
IF #Subreport = 'REPORT1'
BEGIN
DECLARE #Query as varchar(1000)
SET #Query =
'UPDATE CHADotherCharges ' +
' SET Jan = ( ' +
' SELECT Jan FROM '+ #TableName +
' WHERE CHADothercharges.acctcode = '''+ #AccountCode +'' +
' AND ReportName = '+ #ReportName +
' AND acctperiod = '+ convert(varchar(18), #AcctPeriod) +
' AND acctyear = '+ convert(varchar(18), #AcctYear) +
') ' +
'FROM Chadothercharges WHERE type IN(''+'',''SUM'',''-'')'
EXEC (#Query)
END
One obvious problem is this line:
' WHERE CHADothercharges.acctcode = '''+ #AccountCode +'' +
-------------------------------------------------------^
That does nothing. I assume you want to put in a single quote, as ''''.
However, the real way to approach this is by using sp_executesql and using parameters for all the constant values in the query. You can't use this for #TableName, but you can use it for the values in the WHERE.

I can't insert a record in database: "Invalid Column Name"

create PROCEDURE [dbo].[pro_InsertRecord]
#table varchar(30) ,
#field varchar(max) ,
#value varchar(max)
AS
SET NOCOUNT ON
BEGIN
EXEC('INSERT INTO ' + #table + '(' + #field + ') VALUES ( '+ #value +')')
END
I can't insert a record in database but i receive an insert error message as "Invalid Column Name"
my code:
string fieldnames = "Login_UserName, Login_Password, Login_Role_Id";
string fieldvalues = UserName +"','" + Password + "'," + Role ;
com.Common.InsertRecord("Login", fieldnames, fieldvalues);
Instead of
string fieldvalues = UserName +"','" + Password + "'," + Role ;
use
string fieldvalues = "'" + UserName + "','" + Password + "'," + Role ;

How to create stored procedure

How to create stored procedure for this c# statement
String Orders = "INSERT INTO Orders VALUES('" + DDLCustomerID.SelectedValue + "','" + Convert.ToInt32(TxtNetPrice.Text) + "');" + " SELECT SCOPE_IDENTITY();";
SqlCommand command = new SqlCommand(Orders, Connection);
command.CommandType = CommandType.Text;
Connection.Open();
int intID = Convert.ToInt32(command.ExecuteScalar());
String Orderdetails1 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct1.SelectedItem + "','" + Convert.ToInt32(TxtPrice1.Text) + "','" + Convert.ToInt32(TxtQuantity1.Text) + "','" + Convert.ToInt32(TxtTotalPrice1.Text) + "')";
SqlCommand Command1 = new SqlCommand(Orderdetails1, Connection);
Command1.CommandType = CommandType.Text;
Command1.ExecuteNonQuery();
String Orderdetails2 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct2.SelectedItem + " ','" + Convert.ToInt32(TxtPrice2.Text) + "','" + Convert.ToInt32(TxtQuantity2.Text) + "','" + Convert.ToInt32(TxtTotalPrice2.Text) + "')";
SqlCommand Command2 = new SqlCommand(Orderdetails2, Connection);
Command2.CommandType = CommandType.Text;
Command2.ExecuteNonQuery();
String Orderdetails3 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct3.SelectedItem + " ','" + Convert.ToInt32(TxtPrice3.Text) + "','" + Convert.ToInt32(TxtQuantity3.Text) + "','" + Convert.ToInt32(TxtTotalPrice3.Text) + "')";
SqlCommand Command3 = new SqlCommand(Orderdetails3, Connection);
Command3.CommandType = CommandType.Text;
Command3.ExecuteNonQuery();
Response.Write("<script>alert('Successfully Inserted');</script>");
Connection.Close();
How to create stored procedure for this c# statement
The table I created in SQL SERVER is
CREATE TABLE Customers
(
CustomerID INT IDENTITY(1, 1) PRIMARY KEY,
FirstName NVARCHAR(45),
LastName NVARCHAR(45),
Address NVARCHAR(45)
)
CREATE TABLE Orders
(
OrderID INT IDENTITY(1, 1) PRIMARY KEY,
CustomerID INT FOREIGN KEY REFERENCES Customers(CustomerID),
TotalPrice INT
)
CREATE TABLE OrderDetails
(
OrderID INT FOREIGN KEY REFERENCES Orders(OrderID),
ProductName NVARCHAR(45),
Quantity NVARCHAR(45),
Price NVARCHAR(45),
TotalPrice INT
)
I want to create a stored procedure for this statement
This is the SQL code that you need to write :
Syntax for stored procedure :
Create Proc Proc_Name
(
#PARAM1 DATATYPE,
....
)
AS
BEGIN
BODY OF THE SP
END
This is the way to create the stored procedure in SQL.
As you have bunch of queries that you are executing at the single shot.
You also tack care of your transaction.
If suppose your last insert query got EXCEPTION then you above all the queries needs to be rollback & not should be executed.
I have also done rollback in the stored procedure.
CREATE PROC Procedure_Name
(
#Customer_id INT,
#TxtNetPrice FLOAT,
#DDLProduct1 INT,
#TxtQuantity1 FLOAT,
#TxtTotalPrice1 FLOAT,
#TxtPrice1 FLOAT,
#intID INT
)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Orders VALUES(#Customer_id,#TxtNetPrice)
DECLARE #S_ID int;
SET #S_ID = (SELECT SCOPE_IDENTITY())
INSERT INTO
OrderDetails
VALUES(#intID,#DDLProduct1,#TxtPrice1,#TxtQuantity1,#TxtTotalPrice1)
COMMIT
END TRY
BEGIN CATCH
DECLARE #ERROR_MSG NVARCHAR(MAX), #SEVERITY INT, #STATE INT
SELECT #SEVERITY = ERROR_SEVERITY(), #STATE = ERROR_STATE()
, #ERROR_MSG = ERROR_MESSAGE() + ' err src line: ' + CAST( ERROR_LINE() AS NVARCHAR(20)) + ' ' + ISNULL(ERROR_PROCEDURE(), '');
--#ERROR_MSG = ERROR_MESSAGE()
ROLLBACK;
-- RE-THROW EXCEPTION FOR DIAGNOSTIC VISIBILITY
RAISERROR (#ERROR_MSG ,#SEVERITY, #STATE);
RETURN
END CATCH
END

Get SQL Server Job Status

I'm trying to get the status of my jobs in MS SQL Server, the aim is to create an alert in our remote monitoring software if any of the enabled jobs have errored.
Currently I'm using the sys.xp_sqlagent_enum_jobs stored procedure however that seems to show both enabled and disabled jobs, so I tried using the msdb.dbo.sp_help_job, this is exactly what I need but without using the OPENQUERY parameter (which is disabled on the servers) I can't query or capture the results because of the nesting error, I got the same with sp_get_composite_job_info.
So I'm starting to run out of ideas does anyone know of a way to capture this information for query or to store in a able for query later.
I'll include my current code in case it is useful for anyone, it works well returning the number of failed jobs, but if you have a failed job that is disabled this also shows up.
objRecordSet.Open _
"SET NOCOUNT ON " & _
"DECLARE #MaxLength INT " & _
"SET #MaxLength = 50 " & _
"DECLARE #xp_results TABLE ( job_id uniqueidentifier NOT NULL, " & _
"last_run_date nvarchar (20) NOT NULL, " & _
"last_run_time nvarchar (20) NOT NULL, " & _
"next_run_date nvarchar (20) NOT NULL, " & _
"next_run_time nvarchar (20) NOT NULL, " & _
"next_run_schedule_id INT NOT NULL, " & _
"requested_to_run INT NOT NULL, " & _
"request_source INT NOT NULL, " & _
"request_source_id sysname " & _
"COLLATE database_default NULL, " & _
"running INT NOT NULL, " & _
"current_step INT NOT NULL, " & _
"current_retry_attempt INT NOT NULL, " & _
"job_state INT NOT NULL " & _
")" & _
"DECLARE #job_owner sysname " & _
"DECLARE #is_sysadmin INT " & _
"SET #is_sysadmin = isnull (is_srvrolemember ('sysadmin'), 0) " & _
"SET #job_owner = suser_sname () " & _
"INSERT INTO #xp_results EXECUTE sys.xp_sqlagent_enum_jobs #is_sysadmin, #job_owner " & _
"UPDATE #xp_results SET last_run_time = right ('000000' + last_run_time, 6), next_run_time = right ('000000' + next_run_time, 6) " & _
"SELECT count(*) as cnt FROM #xp_results x LEFT JOIN msdb.dbo.sysjobs j ON x.job_id = j.job_id LEFT OUTER JOIN msdb.dbo.syscategories c " & _
"ON j.category_id = c.category_id LEFT OUTER JOIN msdb.dbo.sysjobhistory h ON x.job_id = h.job_id " & _
"AND x.last_run_date = h.run_date AND x.last_run_time = h.run_time AND h.step_id = 0 where h.run_status = 0 ", _
objConnection, adOpenStatic, adLockOptimistic
message = message & "JOBCHECK#" & objRecordSet("cnt") & vbNewLine
Not that hard. Keep in mind SQL Server keeps meta data info at all times on what detail is being done to the server actively. I would do this to find failures in that you could create a proc or function, call it by date range. I gave an example of just the query though for the time being:
use msdb;
declare
#Start int = cast( convert(varchar,
dateadd(ww, datediff(ww, 0, getdate())-1,0) -- last week starting
, 112) as int)
, #End int = cast( convert(varchar,
getdate() -- current datetime
, 112) as int)
;
Select
j.name
, j.description
, cast( cast(jh.run_date as varchar) + ' ' + left(jh.run_time, 2) + ':' + substring( cast(jh.run_time as varchar), 3, 2) as datetime) as TimeRan
, jh.message
, jh.step_id
, jh.step_name
from sysjobs j (nolock)
join sysjobhistory jh (nolock) on j.job_id = jh.job_id
and jh.run_date between #Start and #End
and jh.run_status = 0 -- 0 is failure
Many thanks using help from djangojazz, I was able to do what I wanted:
use msdb;
Select count(*) as cnt
from sysjobs j (nolock)
join sysjobhistory jh (nolock) on j.job_id = jh.job_id
and instance_id = (
select MAX(instance_id)
from sysjobhistory (nolock)
where job_id = j.job_id
)
and j.enabled = 1
and jh.run_status = 0

Is this UPDATE table statement correct in an msdn topic

I have seen this type of UPDATE statement (just like insert statement) in the following msdn topic:
http://msdn.microsoft.com/en-us/library/aa0416cz.aspx#Y2461
UPDATE statement:-
adapter.UpdateCommand = New SqlCommand("UPDATE Customers " &
"(CustomerID, CompanyName) VALUES(#CustomerID, #CompanyName) " & _
"WHERE CustomerID = #oldCustomerID AND CompanyName = " &
"#oldCompanyName", connection)
Is this statement correct or not?
I have tried executing it and it is giving syntax errors.
No, it should be:
UPDATE Customers
SET
CustomerID = #CustomerID,
CompanyName = #CompanyName
WHERE
CustomerID = #oldCustomerID AND
CompanyName = #oldCompanyName
Or to be complete with your sample code, it should be:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName", connection)
Here is another reference for you and this situation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx
That SQL appears to be correct for an INSERT INTO but not for an UPDATE It should read:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers" & _
" SET CustomerID = #CustomerID, CompanyName = #CompanyName)" & _
" WHERE CustomerID = #oldCustomerID AND CompanyName =" & _
" #oldCompanyName", connection)
That SQL is what one would call paramaterized, so that makes this code (lower in the snippet) very important:
adapter.UpdateCommand.Parameters.Add( _
"#CustomerID", SqlDbType.NChar, 5, "CustomerID")
adapter.UpdateCommand.Parameters.Add( _
"#CompanyName", SqlDbType.NVarChar, 30, "CompanyName")
' Pass the original values to the WHERE clause parameters.
Dim parameter As SqlParameter = dataSet.UpdateCommand.Parameters.Add( _
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID")
parameter.SourceVersion = DataRowVersion.Original
parameter = adapter.UpdateCommand.Parameters.Add( _
"#oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName")
parameter.SourceVersion = DataRowVersion.Original
As far as I can see the syntax is not valid. The following gives Incorrect syntax near '('.
I suggest changing it as per Dan's answer.
CREATE TABLE Customers
(
CustomerID INT,
CompanyName VARCHAR(10)
)
DECLARE
#CustomerID INT,
#CompanyName VARCHAR(10),
#oldCustomerID INT,
#oldCompanyName VARCHAR(10)
UPDATE Customers (CustomerID, CompanyName)
VALUES(#CustomerID, #CompanyName)
WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName