Failed to read SERVERPROPERTY - sql-server

The stored procedure has MSSQL server version checking using the SERVERPROPERTY('ProductVersion') property. Depending on what this property returns, the dynamic script is executed appropriately for the installed version.
DECLARE #query NVARCHAR(MAX)
DECLARE #version NVARCHAR(128) = CAST(SERVERPROPERTY('ProductVersion') AS NVARCHAR)
SET #version = SUBSTRING(#version, 1, CHARINDEX('.', #version) - 1)
DECLARE #versionAsInt INT = CAST(#version AS INT)
IF #versionAsInt > 10
SET #query = 'SELECT 1'
ELSE
SET #query = 'SELECT 2'
EXEC sp_executesql #query
But sometimes this check fails and code that doesn't match the installed version is executed, resulting in errors. Usually at this time the server is very heavily overloaded.
I haven't found any information that this property is a problem, but everything indicates that this property can sometimes return null.
Has anyone encountered this problem before and can provide a link to it?

Related

Failed to deploy project. Operation_messages view for the operation identifier '33'

ON the last phase of deploying my SSIS project, received this error. Ran the code
SELECT *
FROM SSISDB.catalog.operation_messages AS OM
WHERE OM.operation_id = 33
Result: failed to deploy the project. Fix the problems and try again later. The specified parameter value string is too long. The string must be no more than 8000 characters.
Please help.
If you are on SQL Server 2008 or newer you can use VARCHAR(MAX)
DECLARE #sql VARCHAR(MAX)
varchar(max) should work just fine, the following is SQL:
declare #cmd varchar(max)
set #cmd = 'print /*' + replicate ('-', 7990);
set #cmd = #cmd + replicate ('-', 7990) + '*/ getdate()';
exec (#cmd)
print datalength (#cmd)

OPENROWSET: sp_executesql statement failing at #param

I am developing a program to pull in the XML file that WordPress enables you to download (essentially a backup copy).
At this point I was automating the process to allow frequent backup of my data on SQL Server, and for some reason I am stuck at developing the query to run the OPENROWSET where the XML file will be located.
DECLARE #SQL NVARCHAR(MAX)
DECLARE #ParamDefinition NVARCHAR(500) = N'#fstring NVARCHAR(MAX)'
DECLARE #string VARCHAR(MAX) =
N'C:\[FilePath]\Reviews\thehesperian2016-07-29.xml'
SET #SQL =
N'INSERT INTO #Temp (Extract_Date, XMLDATA)
SELECT GETDATE()
, A.*
FROM OPENROWSET(BULK #fstring, SINGLE_BLOB, CODEPAGE = ' + '''RAW''' + ') AS A'
EXEC sp_executesql #SQL
, #ParamDefinition
, #fstring = #string
The error:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '#fstring'.
I can turn this into a simple query on a table in the predicate, so I have reason to suspect it is the way the filepath is read.
I've spent a few hours racking my brain trying to figure out why this is wrong. While I COULD use QUOTENAME as in this example in the BULKINSERT, I was hoping to embed all of that in the dynamic SQL (thus still use sp_executesql)
What or why am I doing this wrong? Any help will be greatly appreciated.
- Regards,
ANSWER
OPENROWSET - MSDN declares in its own paragraph:
OPENROWSET does not accept variables for its arguments.
QUOTENAME is sufficient, although I did run a few minor REPLACEfunctions anyways.
The data file path the OPENROWSET function does not allow a parameter. Instead, build the needed string with the literal:
DECLARE #string varchar(MAX) = N'C:\[FilePath]\Reviews\thehesperian2016-07-29.xml';
DECLARE #SQL nvarchar(MAX);
SET #SQL =
N'INSERT INTO #Temp (Extract_Date, XMLDATA)
SELECT GETDATE()
, A.*
FROM OPENROWSET(BULK ' + QUOTENAME(#string, '''') + ', SINGLE_BLOB, CODEPAGE = ''RAW'') AS A';
EXEC sp_execute #SQL;
--EXECUTE(#SQL);
UPDATE:
Added QUOTENAME in case the provided file path is from an untrusted source. Also, note that OPENROWSET queries are not autoparameterized. It makes no difference whether one executes the query with sp_executesql or EXECUTE here.

Using dynamic sql in openrowset produces error

I need to create a stored procedure that gets a path as a parameter and inserts from file into table via OPENROWSET command.
After lots of searching and trying, I learned that OPENROWSET does not
support parameters and thus needs to be called with dynamic SQL.
That is the part that doesn't work, it shows me a strange error.
It could be caused by the OPENROWSET not accepting the string parameter
but - I saw many code snippets that are built similarly and users say they work.
Please help me understand what I'm missing here and how do I make this work?
Here is my code:
Declare #string varchar(MAX) = 'C:\Users\akoga_000\Desktop\test1.xlsx'
DECLARE #sqlString AS varchar(MAX)=
'insert into gameIt_DBSummer.dbo.tblUser
select * from openrowset(
''Microsoft.ACE.OLEDB.12.0'',
''EXCEL 12.0;DataBase=''
'+cast(#string as varchar(max))+'
'';Extended Properties="EXCEL 12.0 Xml;HDR=YES'',
''SELECT * FROM [Sheet1$]''
)';
EXEC (#sqlString)
//I tried also with EXEC sp_executesql and a nvarchar variable among other options
Here is the error:
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 'C:'.
I think you are getting that error because you need double extra '' character surrounding the path (#string variable). Try this:
Declare #string varchar(MAX) = 'C:\Users\akoga_000\Desktop\test1.xlsx'
DECLARE #sqlString AS varchar(MAX)=
'insert into gameIt_DBSummer.dbo.tblUser
select * from openrowset(
''Microsoft.ACE.OLEDB.12.0'',
''EXCEL 12.0;DataBase=''''
'+#string+'
'''';Extended Properties="EXCEL 12.0 Xml;HDR=YES'',
''SELECT * FROM [Sheet1$]''
)';
select #sqlString

Passing concat query parameters to SQL OPENQUERY

Due to the constraints within the workplace I have to use a local stored procedure to call another remote stored proc on a linked sql server, however the problem lies in passing a necessary parameter to the remote stored proc.
This is the query I constructed:
select *
from OPENQUERY([REMOTE_SRVR],'exec db.dbo.dwStoredProc_sp ''#id''')
In order to pass #id to the remote stored proc I understand I could concatenate the above as a string and then use exec
Something along the lines of:
set #query = 'select * from OPENQUERY([REMOTE_SRVR], ''EXEC db.dbo.dwStoredProc_sp '' #id '''''
exec(#query)
I cannot get the local stored proc to successfully call the other. The single quote mess doesn't help!
I get the error: Could not find stored procedure 's'
To help with the quote mess I like to do this in steps. It is more code but easier to understand. I am not sure from your example if #id is an integer. In that case you can lose the double quotes around __ID__.
set #query = 'EXEC db.dbo.dwStoredProc_sp ''__ID__'''
set #query = REPLACE(#query,'__ID__',#id)
set #query = REPLACE(#query,'''','''''')
set #query = REPLACE('SELECT * FROM OPENQUERY([REMOTE_SRVR], ''__REMOTEQUERY__'')','__REMOTEQUERY__',#query)
You could avoid dynamic queries by simply by using EXEC (..., ParamValue) AT LinkedServer (see product's documentation, example [L. Using a parameter with EXECUTE and AT linked_server_name]):
1) On target server:
CREATE PROCEDURE dbo.Proc1( #id NVARCHAR(50) )
AS
SELECT #id AS [id];
GO
2) On the source server you create the linked server and then you can call the stored procedure using EXEC ... AT ... syntax:
DECLARE #p1 NVARCHAR(50);
SET #p1 = N'DROP TABLE dbo.CocoJambo'
EXECUTE (N'dbo.Proc1 ? ' , #p1 ) AT LOCALINKEDSEREV
Output:
id
------------------------
DROP TABLE dbo.CocoJambo

SQL Server changed my strings before running the query

I try to select some special records contain special characters but SQL Server changes my string characters before it running the query.
For example:
DECLARE #param NVARCHAR(30)
SET #param=N'¤÷þ'--this is my special string that i want to be searched exactly.
DECLARE #TSQL varchar(8000)
SET #TSQL = 'SELECT * FROM MyTable WHERE MyFieldName LIKE %' + #param + '% '
PRINT #TSQL
--EXECUTE (#TSQL)
But in the result(print) I see:
SELECT * FROM MyTable WHERE MyFieldName LIKE '%¤÷þ?%'
As you see some part of string converted to (?) character, this problem cause my SELECT command return null value.
I try to change collation of the database that I run the query to:
SQL_Latin1_General_CP1_CI_AS
It work fine with some special string but it also does not support all of my strings.
So, question is here: how can I tell SQL Server, please don't change my string ascii codes?
Is there any way (or any collation) to say SQL Server that see an string exactly as it is in reality?
PS: I am using SQL Server 2008 R2.
If you have special characters that need to be preserved, use Unicode strings of type NVARCHAR instead of VARCHAR - it's that simple .....
DECLARE #param NVARCHAR(30)
SET #param = N'¤÷þ'--this is my special string that i want to be searched exactly.
DECLARE #TSQL NVARCHAR(4000) -- <=== use NVARCHAR here
SET #TSQL = N'SELECT * FROM MyTable WHERE MyFieldName LIKE %' + #param + N'% '
PRINT #TSQL
Then your special characters will be preserved as entered ....
And as others have pointed out: concatenating together your SQL statements like this is never a good idea - it opens up your code to potential SQL injection attacks. You should use parameterized queries and sp_executesql which allows you to define and supply paramters to your queries.
DECLARE #TSQL varchar(8000)
varchar(8000) cannot represent ¤÷þ. Just keep doing what you're doing with #param; use something NVARCHAR based.
As usr correctly points out, you should really be using sp_executesql and its ability to specify parameters. From the documentation:
DECLARE #IntVariable int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
/* Build the SQL string one time.*/
SET #SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = #BusinessEntityID';
SET #ParmDefinition = N'#BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET #IntVariable = 197;
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#BusinessEntityID = #IntVariable;

Resources