SQL Server Print Output to Chef inspec - sql

The SQL Server print messages are not taken into chef inspec for validation. Do we have an option to validate.
Below chef inspec sample code donot take the SQL Server print message.
sql = mssql_session(user: 'sa', password: 'Test')
describe sql.query("
-- #5.2 - Set the ''default trace enabled'' Server Configuration Option to 1
IF EXISTS (SELECT name, CAST(value as int) as value_configured, CAST(value_in_use as int) as value_in_use FROM sys.configurations WHERE name = 'default trace enabled' and (value=1 and value_in_use=1))
BEGIN
PRINT 'OK'
END
ELSE
PRINT 'NOT OK'") do
its("value") { should eq 'OK' }
end
end

Instead of PRINT 'OK' use SELECT 'OK' AS value / SELECT 'NOT OK' AS value.
Programmatically getting a hold of PRINT messages can be done but you need code to listen to the connection's InfoMessage event. Basically you'd need to dig into the code for either mssql_session or sql.query... which you probably don't want to do.

You can modify your statement to directly return OK or NOT OK, as given below. SELECT returns the resultset back. Print does not return result set back. The drivers have to read it differently using InfoMessage event. Read more.
Better to go for SELECT statement, as suggested by #user2845090.
SELECT CASE WHEN
EXISTS (SELECT name
, CAST(value as int) as value_configured
, CAST(value_in_use as int) as value_in_use
FROM sys.configurations WHERE name = 'default trace enabled'
and (value=1 and value_in_use=1)) THEN 'OK' ELSE 'NOT OK'
END
Or
SELECT IIF(EXISTS((SELECT name
, CAST(value as int) as value_configured
, CAST(value_in_use as int) as value_in_use
FROM sys.configurations WHERE name = 'default trace enabled'
and (value=1 and value_in_use=1)),'OK','NOT OK')

Related

SQL to get whole words till end from the keyword

Consider I have text from the field (notes) as below:
Please check http://example.com
I want a SQL query which fetches the link part only. That is to find keyword http and print till the last.
Output:
http://example.com
Also if the text field doesnt have any link, can we print NA?
CASE WHEN sys like '%Clo%'
THEN RIGHT( i.notes,LEN(i.notes) - CHARINDEX('http',i.notes,1)+1)
ELSE "No Link Available" END AS Cl_Link
For SQL Server you can consider this below logic-
DECLARE #T VARCHAR(MAX) = 'Please check http://example.com'
SELECT RIGHT(#T,LEN(#T) - CHARINDEX('http:',#T,1)+1)
For MySQL-
SET #T = 'Please check http://example.com';
SELECT RIGHT(#T,LENGTH(#T) - POSITION("http:" IN #T)+1)
In case of select query using table, queries will be-
-- SQL Server
SELECT RIGHT(column_name,LEN(column_name) - CHARINDEX('http:',column_name,1)+1) FROM your_table_name
-- MySQL
SELECT RIGHT(column_name,LENGTH(column_name) - POSITION("http:" IN column_name)+1) FROM your_table_name
To apply 'NA' when no link available, please use the below logic-
DECLARE #T VARCHAR(MAX) = 'Please check http://example.com'
SELECT
CASE
WHEN CHARINDEX('http:',#T,1) >= 1 THEN RIGHT(#T,LEN(#T) - CHARINDEX('http:',#T,1)+1)
ELSE 'NA'
END
Below is the query for your reference, executed on mysql:
SELECT substr(columnname,locate('http',columnname)) as link
FROM `tablename` where column=value
For MySQL try this:
select REGEXP_SUBSTR(text_column, 'http\:\/\/([\\w\\.\\S]+)') from mytest

Importing SQL Server 2008 stored procedure into Excel 2016 I get an error

I am importing a stored procedure from SQL Server 2008 into Excel 2016, and get an error when I execute it in Excel:
Error converting data type nvarchar to date
This is the stored procedure [LA_VOTER].[Temp].[dmv_import]:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Arash B
-- Create date: 6/5/2018
-- Description: test for creating dynamic 'Data Entry Signature Verification' worksheeet
-- =============================================
ALTER PROCEDURE [Temp].[dmv_import]
#date DATE = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #date_work DATE
IF #date IS NULL
SET #date_work = GETDATE()
ELSE
SET #date_work = #date
/*count of processed*/
SELECT
vi.import_code as 'DMV Category',
SUM(CASE WHEN CONVERT(date, vi.createdate, 101) = #date_work THEN 1 ELSE 0 END) AS 'received',
SUM(CASE WHEN CONVERT(date, vi.processed_date, 101) = #date_work THEN 1 ELSE 0 END) AS 'processed'
FROM
DIMSNet.dbo.voter_import vi
WHERE
vi.import_type IN ('DMV')
AND import_code < 13
GROUP BY
import_code
END
I access it in Excel through Data – From Other Sources shown below.
I select from SQL and enter “slavote-dr1” for server to connect to; “DIMSNet” the selected table and any random table as instructions indicated.
Once I reach the “Import Data” pop-up window I select the Cell in the excel worksheet I want to drop the table onto and click on the “properties” button.
Chose the “Definition” tab and changed command type to “SQL”.
Entered the executable in the “Command Text box”. Since the database use to connect I inserted the full path for the stored procedure on the command line.
Execute "LA_VOTER"."Temp"."dmv_import" ","
I click “OK” and return to the “Import Data” window. I click “Ok” to import the table.
I get the error stated above.
I looked at the script and could not see where this error was coming from. Is there anything that you can suggest?
PS. Added 6/12/18 ----- The SP runs fine in SQL. It is only when importing into Excel that the issue occurs.
The failure is undoubtedly in the stored procedure. It is almost certainly in these lines:
sum(case when convert(date, vi.createdate, 101) = #date_work then 1 else 0 end) as received,
sum(case when convert(date, vi.processed_date, 101) = #date_work then 1 else 0 end) as processed
I would suggest that you find the problems in the data and fix them. You can possibly fix the problem by doing:
sum(case when isdate(vi.createdate) = 0 then 0
when convert(date, vi.createdate, 101) = #date_work then 1
else 0
end) as received,
sum(case when isdate(vi.processed_date) = 0 then 0
when convert(date, vi.processed_date, 101) = #date_work
then 1
else 0
end) as processed
OK used a different method and got it working.
Used the "From Microsoft Query" and my Execute script was:
{CALL LA_VOTE.tmp.dmv_import(?)} and it imported the data I needed into the fields I wanted.
http://codebyjoshua.blogspot.com/2012/01/get-data-from-sql-server-stored.html

SQL Server : query if table exist

I have the following query:
SELECT
COUNT(*) over () as countNum,
[F1] AS STANDARDandOBJ,
[F2] AS CLUSTER,
[F3] AS OBJECTIVE,
[F4] AS EXTRA0
IF COL_LENGTH([tmpExcelDB].[dbo].['Blahsing$'], [F5]) IS NOT NULL
BEGIN
print 'exists'
END
ELSE
BEGIN
print 'Nope'
END,
CONCAT([F1], [F2]) AS combined
FROM
[tmpExcelDB].[dbo].['Blahsing$']
WHERE
LOWER(F3) NOT LIKE 'course tools-%'
But it seems that I have an error of:
Incorrect syntax near ','.
Which is pointing to row:
,CONCAT([F1], [F2]) AS combined
How does this need to be formatted in order to work?
You can't use IF inside a SELECT, you need a CASE expression. Also, it doesn't make sense to use PRINT inside a column:
SELECT
COUNT(*) over () as countNum
,[F1] AS STANDARDandOBJ
,[F2] AS CLUSTER
,[F3] AS OBJECTIVE
,[F4] AS EXTRA0
,CASE
WHEN COL_LENGTH('[tmpExcelDB].[dbo].[''Blahsing$'']', '[F5]') IS NOT NULL
THEN 'exists'
ELSE 'Nope'
END
,CONCAT([F1], [F2]) AS combined
FROM [tmpExcelDB].[dbo].['Blahsing$']
WHERE
LOWER(F3) NOT LIKE 'course tools-%';
SELECT
COUNT(*) over () as countNum
,[F1] AS STANDARDandOBJ
,[F2] AS CLUSTER
,[F3] AS OBJECTIVE
,[F4] AS EXTRA0 ,
( CASE When COL_LENGTH([tmpExcelDB].[dbo].['Blahsing$'], [F5]) IS NOT NULL
THEN
'exists'
ELSE
'Nope'
END),
CONCAT([F1], [F2]) AS combined
FROM [tmpExcelDB].[dbo].['0812 Orientation to Nursing$']
WHERE LOWER(F3)NOT LIKE 'course tools-%'
Couple things:
IF...ELSE is not supported in a select list, use CASE instead
PRINT is not supported in a select list, just the literal string value is needed
See the CASE Documentation for a relevant example.

Case, Is Null and a parameter

I have a query that i'd like to have display "0" if the "Tip" is "NULL" otherwise just display the tip. This is my query:
SELECT t1.sName ,
t1.sLocationDesc ,
t1.sOtherNumber ,
t1.RegHours ,
t1.OTHours ,
CASE
WHEN t2.EmployeeHours / t3.DepartmentHrs * #Tip IS NULL THEN 0
ELSE t2.EmployeeHours / t3.DepartmentHrs * #Tip
END AS Tip
I receive an error:
Incoming Tabular data stream (TDS) remote procedure call (RPC)
protocal stream is incorrect. Parameter 3 ("#Tip") User-defined type
has an invalid user type specified..
Any help here?
Why do you want to use case
just try this
SELECT t1.sName,
t1.sLocationDesc,
t1.sOtherNumber,
t1.RegHours,
t1.OTHours,
ISNULL(t2.EmployeeHours / t3.DepartmentHrs * #Tip,0) AS 'Tip'
BTW I feel the error is not due to your case statement
Try this:
SELECT t1.sName, t1.sLocationDesc, t1.sOtherNumber, t1.RegHours, t1.OTHours,
CASE WHEN (#Tip IS NULL OR #Tip=0) THEN 0 ELSE
t2.EmployeeHours/t3.DepartmentHrs * #Tip END AS Tip

How to get current instance name from T-SQL

How can I get the SQL Server server and instance name of the current connection, using a T-SQL script?
Just found the answer, in this SO question (literally, inside the question, not any answer):
SELECT ##servername
returns servername\instance as far as this is not the default instance
SELECT ##servicename
returns instance name, even if this is the default (MSSQLSERVER)
How about this:
EXECUTE xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl',
#value_name='MSSQLSERVER'
This will get the instance name as well. null means default instance:
SELECT SERVERPROPERTY ('InstanceName')
http://technet.microsoft.com/en-us/library/ms174396.aspx
SELECT ##servername will give you data as server/instanceName
To get only the instanceName you should run select ##ServiceName query .
Why stop at just the instance name? You can inventory your SQL Server environment with following:
SELECT
SERVERPROPERTY('ServerName') AS ServerName,
SERVERPROPERTY('MachineName') AS MachineName,
CASE
WHEN SERVERPROPERTY('InstanceName') IS NULL THEN ''
ELSE SERVERPROPERTY('InstanceName')
END AS InstanceName,
'' as Port, --need to update to strip from Servername. Note: Assumes Registered Server is named with Port
SUBSTRING ( (SELECT ##VERSION),1, CHARINDEX('-',(SELECT ##VERSION))-1 ) as ProductName,
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
SERVERPROPERTY('ProductMinorVersion') AS ProductMinorVersion,
SERVERPROPERTY('ProductBuild') AS ProductBuild,
SERVERPROPERTY('Edition') AS Edition,
CASE SERVERPROPERTY('EngineEdition')
WHEN 1 THEN 'PERSONAL'
WHEN 2 THEN 'STANDARD'
WHEN 3 THEN 'ENTERPRISE'
WHEN 4 THEN 'EXPRESS'
WHEN 5 THEN 'SQL DATABASE'
WHEN 6 THEN 'SQL DATAWAREHOUSE'
END AS EngineEdition,
CASE SERVERPROPERTY('IsHadrEnabled')
WHEN 0 THEN 'The Always On Availability Groups feature is disabled'
WHEN 1 THEN 'The Always On Availability Groups feature is enabled'
ELSE 'Not applicable'
END AS HadrEnabled,
CASE SERVERPROPERTY('HadrManagerStatus')
WHEN 0 THEN 'Not started, pending communication'
WHEN 1 THEN 'Started and running'
WHEN 2 THEN 'Not started and failed'
ELSE 'Not applicable'
END AS HadrManagerStatus,
CASE SERVERPROPERTY('IsSingleUser') WHEN 0 THEN 'No' ELSE 'Yes' END AS InSingleUserMode,
CASE SERVERPROPERTY('IsClustered')
WHEN 1 THEN 'Clustered'
WHEN 0 THEN 'Not Clustered'
ELSE 'Not applicable'
END AS IsClustered,
'' as ServerEnvironment,
'' as ServerStatus,
'' as Comments
I found this:
EXECUTE xp_regread
#rootkey = 'HKEY_LOCAL_MACHINE',
#key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
#value_name = 'InstalledInstances'
That will give you list of all instances installed in your server.
The ServerName property of the SERVERPROPERTY function and ##SERVERNAME return similar information. The ServerName property provides the Windows server and instance name that together make up the unique server instance. ##SERVERNAME provides the currently configured local server name.
And Microsoft example for current server is:
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
This scenario is useful when there are multiple instances of SQL Server installed on a Windows server, and the client must open another connection to the same instance used by the current connection.
To get the list of server and instance that you're connected to:
select * from Sys.Servers
To get the list of databases that connected server has:
SELECT * from sys.databases;
Just to add some clarification to the registry queries. They only list the instances of the matching bitness (32 or 64) for the current instance.
The actual registry key for 32-bit SQL instances on a 64-bit OS is:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
You can query this on a 64-bit instance to get all 32-bit instances as well. The 32-bit instance seems restricted to the Wow6432Node so cannot read the 64-bit registry tree.
You can get your server name, machine name and instance name with Transact-SQL(T-SQL) as shown below:
SELECT ##SERVERNAME -- DESKTOP-OVPADTC\SQLEXPRESS
SELECT SERVERPROPERTY ('ServerName') -- DESKTOP-OVPADTC\SQLEXPRESS
SELECT HOST_NAME() -- DESKTOP-OVPADTC
SELECT SERVERPROPERTY ('MachineName') -- DESKTOP-OVPADTC
SELECT ##SERVICENAME -- SQLEXPRESS
SELECT SERVERPROPERTY ('InstanceName') -- SQLEXPRESS
another method to find Instance name- Right clck on Database name and select Properties, in this part you can see view connection properties in left down corner, click that then you can see the Instance name.