Error in SQL stored procedure - sql

I am getting the following error when I execute my stored procedure:
Msg 102, Level 15, State 1, Line 6Incorrect syntax near '2011'.(1 row(s) affected)
Here is the stored procedure:
ALTER PROCEDURE [dbo].[DeliveryFileNames]
AS
BEGIN
SET NOCOUNT ON;
declare #SQL nvarchar(4000)
Create Table #DelivTemp(
Style nvarchar(50),
Material nvarchar(50),
Filename nvarchar(100),
delivered_date date)
set #SQL=
N'insert into #DelivTemp
Select distinct Style,Material,filename
from OPENQUERY(GCS_PRODUCTION,
''SELECT LEFT(FILENAME,locate(''''_'''',FILENAME)-1)as Style,
substring_index(filename,''''_'''',2)as Material,filename,
delivered_date FROM view_delivery_log
where delivered_date > ''2011%'' order by Style '')'
exec (#SQL)
drop table dbo.DelivFN
Select * into dbo.DelivFN
from #DelivTemp
END
I am using OpenQuery to update a SQL table from a linked server on SQL Server 2008 R2.
I know that the underscore is a real issue, but I have tried a plethora of options including \, % and both single and double quotes.
Regardless I am getting the same result. I can run the query independently of the stored procedure and achieve the correct results. The filename field referenced several times is formatted 00000000_ABC4_A.png. I am using the underscore to identify the components of the file name that I need for my reporting purposes.

In addition to the the logical error of your date comparison using the % that the others have pointed out, your current issue is a syntactical error.
Since you've got a dynamic sql statement contained within another dynamic sql statement... you'll need to double-escape all of your single quotes... which you did in most of the query, except for the following line:
where delivered_date > ''2011%'' order by Style '')'
Properly escaped, would be:
where delivered_date > ''''2011%'''' order by Style '')'
Which raises the question... why are you building up the string to execute dynamically, instead of just calling the statement directly?

It's the syntax of ''2011%''. This is not a valid date. % being a wildcard means the compiler can't know what to compare against in the WHERE clause. You'd need to use an actual date: i.e. ''2011_01_01'' so the compiler can know what to compare against

I believe the stored proc exec runs under a different session, therefore you won't have access to the temp table anyway. So, it won't matter if you get that sql statement to run. You could always use YEAR(delivered_date) > 2011.
Another approach would be to use the fqn for the linked server to select into and bypass the temp table all together:
SELECT LEFT(FILENAME,locate('_',FILENAME)-1)as Style,
substring_index(filename,'_',2)as Material,filename,delivered_date
FROM [linked_server_name].[db_name].[dbo].view_delivery_log
into dbo.DelivFN

Related

Sybase - How To Output Variable Contents To File

I'm writing a procedure in Sybase using Interactive SQL. The proc contains several SELECT statements that store the results in variables, eg
DROP VARIABLE IF EXISTS #totalRows;
CREATE VARIABLE #totalRows LONG VARCHAR;
SELECT COUNT(*) INTO #totalRows FROM <MyTable>;
I'd like to be able to output the results of this query to a CSV file but I get an error when trying to run the following statement
DROP VARIABLE IF EXISTS #totalRows;
CREATE VARIABLE #totalRows LONG VARCHAR;
SELECT COUNT(*) INTO #totalRows FROM <MyTable>;
OUTPUT TO 'C:\\temp\\TEST.CSV' FORMAT ASCII DELIMITED BY ';' QUOTE '' WITH COLUMN NAMES;
The error reads
Could not execute statement.
Syntax error near 'OUTPUT' on line 4.
SQLCODE=-131, ODBC 3 State="42000".
Line 1, column 1
If I remove the OUTPUT TO section of the query it runs fine. Is it possible in Sybase to write the contents of a variable to an external file in this manner?
Seems like, 'OUTPUT' clause is not supported by Sybase.
As a workaround, you may run this query using some text-based tool (like sqlite) and redirect (>) the output into file, if you happen to use linux box at your client end.
Or, you may add ODBC data source (which will require sybase ODBC-driver) corresponding to your DB in Windows and use MS Excel embedded tool Microsoft Query (Data -> From other sources -> From Microsoft Query) in order to export your query result directly into excel datasheet, which you may save as CSV.
OUTPUT TO is a dbisql command, i.e. a directive for the dbisql client utility. It is not a SQL statement. If you try to execute this with anything other than dbisql, you'll get an error.
BTW -- I believe the OUTPUT clause must follow the semicolon that terminates the SELECT stmt, i.e. not have a line break in between.
Need add select variable before output statement
DROP VARIABLE IF EXISTS #totalRows;
CREATE VARIABLE #totalRows LONG VARCHAR;
SELECT COUNT(*) INTO #totalRows FROM <MyTable>;
SELECT #totalRows; --select variable before output
OUTPUT TO 'C:\\temp\\TEST.CSV' FORMAT ASCII DELIMITED BY ';' QUOTE '' WITH COLUMN NAMES;

Creating a view in tempdb in SQL Server through a post request

Since I need to send the query statement through a http post request there are certain limitations.
1. It should be a one liner
2. it should be created in tempdb since i am going to drop it afterwards.
since SQL server takes CREATE VIEW statement only in new line I am feeding new line characters to the statement. here is the statement:
DECLARE #NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10); ('USE tempdb;' +#NewLineChar + 'GO' +#NewLineChar +'CREATE VIEW temp_view AS select name from sys.databases')
This query gives me following error:
Msg 102, Level 15, State 1.
Incorrect syntax near 'USE tempdb;'. (Line 1)
what could be the problem ?
Thanks
edit: The same query works like this
USE tempdb;
GO
CREATE VIEW temp_view AS select name from sys.databases
where is the syntax error?
Since SQL server takes CREATE VIEW statement only in new line I am feeding new line characters to the statement.
I have never heard of such a requirement. What the documentation does state is: The CREATE VIEW must be the first statement in a query batch.
The statement you have in your question doesn't make sense. You can't just drop a VARCHAR in SSMS and expect SQL Server to just execute it.
What you probably want is something like the following:
USE tempdb;
DECLARE #stmt NVARCHAR(MAX)=N'CREATE VIEW temp_view AS SELECT name FROM sys.databases;';
EXECUTE sp_executesql #stmt;
Or in one line:
USE tempdb;DECLARE #stmt NVARCHAR(MAX)=N'CREATE VIEW temp_view AS SELECT name FROM sys.databases;';EXECUTE sp_executesql #stmt;
This is a bit long for a comment.
You can create a view in the current database with a name like _temp_<something>. You can even include session information if you want to emulate temporary tables.
Or, create a temporary table with no rows:
select top 0 *
into #temp
from <whatever>;
You can access the structure of this table.
If you are using a very recent version of SQL Server, use sp_describe_first_result_set (see here).

Dynamically creating the IN clause in a stored procedure [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Need help in dynamic query with IN Clause
I am using SQL server 2008 and this is the problem that I am facing. I have a table named Cars with a column Company. Now I have a stored procedure that looks something like this
CREATE PROCEDURE FindCars (#CompanyNames varchar(500))
AS
SELECT * FROM Cars WHERE Company IN (#CompanyNames)
I tried something like this and failed
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
exec FindCars #CompanyNames
I dont get any rows returned. When I do the following
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
Select #CompanyNames
I get the following result
'Ford','BMW'
and if I replace this value in the select statement inside the stored procedure, it works
SELECT * FROM Cars where Company in ('Ford','BMW')
Thus I think that the stored procedure seems to be treating 'Ford','BMW' as one string rather than an array. Could someone please help me with this. How do I dynamically construct the string/array required in the IN clause of the select statement inside the stored procedure.
You are right, you created one string, and that is being processed as a list of strings that contains one string. The commas are just characters in that one string. The only equivilent to an array in SQL Server is a table.
For example; WHERE x IN (SELECT y FROM z).
For this reason many people create a SPLIT_STRING() function that returns a table of items from a given comma delimitted string...
WHERE x IN (SELECT item FROM dbo.split_string(#input_string))
There are many ways to implement that split string. Some return strings, some cast to integers, some accept a second "delimiter" parameter, etc, etc. You can search the internet for SQL SERVER SPLIT STRING and get many results - Including here in StackOverflow.
An alternative is to use dynamic SQL; SQL that writes SQL.
SET #sql = 'SELECT * FROM x WHERE y IN (' + #input_string_list + ')'
SP_EXECEUTESQL #sql
(I recommend SP_EXECUTESQL over just EXEC because the former allows you to use parameterised queries, but the latter does not.)

MySQL - Using stored procedure results to define an IN statement

I'd like to use a stored procedure to define the IN clause of a select statement.
This is (a simplified version of) what I'm trying to do:
SELECT *
FROM myTable
WHERE columnName IN (CALL myStoredProc)
myStoredProc performs some complicated logic in the database and returns a list of possible matching values for columnName. The statement above does not work obviously. The select statement may be performed in another stored procedure if that makes a difference.
Is this at all possible in mySQL?
What return type does your current stored procedure have? You are speaking of "a list", so TEXT?
Maybe there's an easier way, but one thing you can do (inside another stored procedure) is to build another query.
To do that, we need to work around two limitations of MySQL: a) To execute dynamic SQL inside a stored procedure, it needs to be a prepared statement. b) Prepared statements can only be created out of user variables. So the complete SQL is:
SET #the_list = myStoredProc();
SET #the_query = CONCAT('SELECT * FROM myTable WHERE columnName IN (' , #the_list , ')');
PREPARE the_statement FROM #the_query;
EXECUTE the_statement;
If you're talking about returning a result set from a stored routine and then using it as table, that is not possible. You need to make a temporary table to work around this limitation.

Why can't use INSERT EXEC statement within a stored procedure called by another stored procedure?

First I try to explain the circumstances.
I store the the filter expression in one column separated by line breaks. The base idea was this:
SELECT
'SELECT ''' + REPLACE(topic_filter,CHAR(10),''' UNION ALL SELECT ''') + ''''
FROM dbo.topic_filter T
WHERE
T.id = #id
FOR XML PATH('')
After this I simply execute this string to put the datas into a temp table.
My problem starts here.
The snippet is in a stored procedure and used by multiple stored procedures to generate the base source to fill.
Approach 1:
Call this sp from another SP to fill a temp table.
Result 1:
An INSERT EXEC statement cannot be nested.
(If I call simply with exec dbo... style the code is working. I only get the error if I try to call within a stored procedure)
Approach 2:
I put the code above into a table values function.
Result 2:
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
(The function itself don't compiled)
Thanks,
Péter
In the meantime I managed to solve the problem (with help :) ). The solution is simple:
exec('insert into t2 ' + #str)
Where #str contains a select statement.
I don't know why but this way there is no error. The method I call the stored procedure:
SET #exec = 'exec dbo.trFilterTopic ''' + #id+ ''',null,null,1'
INSERT INTO #filtered
exec (#exec)
I hope I spare some time to other folks with this solution.
Bye,
Péter
It is an SQL Server restriction. You cannot have a nested insert exec (I'm not sure why).
If you go:
insert into t(value)
exec dbo.proc
, and inside dbo.proc you have
insert into t2(value2)
exec(#str)
, then it will not run.
Consider different ways of passing tables around, such as temporary tables or table-valued parameters.
Functions on SQL Server have limitations,
they arenot procedures, you can't use dynamic SQL like 'EXECUTE STRING', 'INSERT EXEC'...