Numeric value is not recognized error in OPENQUERY - sql

I have the following stored procedure. When it runs, i get the error
returned message "Numeric value '+#requestno+' is not recognized" . I believe the setting of the variable requestno is not working. How do i resolve it?
Declare #requestno nvarchar(max)
Set #requestno = (Select requestno from table1 where condition met)
SELECT * INTO tempdb..#temptable FROM OPENQUERY (SalesDb,
'SELECT *
FROM TableinAnotherDb
WHERE 1=1
and request_number=''+#requestno+'' Order by some column'
)
Thank you

prepare you query in advance:
Declare #queryStr nvarchar(max)
SELECT #queryStr ='SELECT *
FROM TableinAnotherDb
WHERE 1=1
and request_number='+ requestno+' Order by some column'
FROM table1
WHERE condition met
SELECT * INTO tempdb..#temptable FROM OPENQUERY (SalesDb,#queryStr)

Related

SQL return values if row count > X

DECLARE #sql_string varchar(7000)
set #sql_string = (select top 1 statement from queries where name = 'report name')
EXECUTE (#sql_string)
#sql_string is holding another SQL statement. This query works for me. It returns all the values from the query from the statement on the queries table. From this, I need to figure out how to only return the results IF the number of rows returned exceeds a threshold (for my particular case, 25). Else return nothing. I can't quite figure out how to get this conditional statement to work.
Much appreciated for any direction on this.
If all the queries return the same columns, you could simply store the data in a temporary table or table variable and then use logic such as:
select t.*
from #t t
where (select count(*) from #t) > 25;
An alternative is to try constructing a new query from the existing query. I don't recommend trying to parse the existing string, if you can avoid that. Assuming that the query does not use CTEs or have an ORDER BY clause, for instance, something like this should work:
set #sql = '
with q as (
' + #sql + '
)
select q.*
from q
where (select count(*) from q) > 25
';
That did the trick #Gordon. Here was my final:
DECLARE #report_name varchar(100)
DECLARE #sql_string varchar(7000)
DECLARE #sql varchar(7000)
DECLARE #days int
set #report_name = 'Complex Pass Failed within 1 day'
set #days = 5
set #sql_string = (select top 1 statement from queries where name = #report_name )
set #sql = 'with q as (' + #sql_string + ') select q.* from q where (select count(*) from q) > ' + convert(varchar(100), #days)
EXECUTE (#sql)
Worked with 2 nuances.
The SQL returned could not include an end ";" charicter
The statement cannot include an "order by" statement

Store value from SELECT statement into variable on SQL Server

I am trying to select value from the system object,synonyms and then store into #variable. Then I can select data from #variable without caring the server.
However it keeps saying that I need to declare scalar variable. Can anyone help?
DECLARE #variable NVARCHAR(100)
SELECT #variable = name
FROM sys.synonyms
WHERE base_object_name = '[ABC].[dbo].[tblABC]'
SELECT * FROM #variable
Your query selects all names and successively stores them in the variable, meaning that each name overwrites the previously stored name, so only the last selected name is available in the variable when the SELECT statement terminates. If you want a variable that you can query like a temporary table, you will have to declare a table variable and insert the names into that "table", afterwards you can run a select statement against that variable:
Declare #variable table (name nvarchar(128));
INSERT INTO #variable (name)
SELECT name
FROM sys.synonyms
where base_object_name = '[ABC].[dbo].[tblABC]';
select * from #variable;
But: Also on this query, the server will "care".
The problem is that you need to return only one value to the variable. In this way:
Declare #variable nvarchar(100)
#variable = (SELECT TOP(1) name -- getting only one registry
FROM sys.synonyms where base_object_name =
'[ABC].[dbo].[tblABC]')
select #variable
You have to do next :
declare #names table ( name nvarchar(100 ) );
insert #names(name)
select name
FROM sys.synonyms
where base_object_name = '[ABC].[dbo].[tblABC]';
select * from #names

Declaring the 'AND' condition in a variable

Please tell me if this isn't the right way to approach the problem.
I want to declare the code after my AND condition in a variable.. the code is:
SELECT * FROM MyTable
WHERE Key = '12345'
AND (Condition1 or Condition2 or Condition3)
I am hoping to achieve something like this:
DECLARE #Condition
SET #Condition = 'Condition1 or Condition2 or Condition3'
SELECT * FROM MyTable
WHERE Key = '12345'
AND #Condition
The AND operator expects a boolean expresssion so this doesn't work. Please tell me how I can achieve this..
The idea is that I can store the #Condition in a variable table (varName, varValue) and fetch it from there whenever I want to use it in the code (kinda like a global variable). Please also let me know if the performance of the code will be affected if I follow this approach.
You need to use dynamic sql:
declare #sql nvarchar(max);
set #sql = 'select * from mytable where [key] = #key and #condition';
set #sql = replace(#sql, '#condition', #condition);
exec sp_executesql #sql, N'#key varchar(255)', #key = '12345';
When you put #condition in the where clause it is treated as a string. That's all. No semantic analysis.
I'm wondering if you can create a table variable with your conditions... Since you're not very specific about what those conditions are, it's hard to tell if something like this would work, but this is an approach I sometimes use:
declare #conditions table (condition nvarchar(255), value bit);
insert into #table (condition, value)
select condition, value
from (
values ('Less than x', 1), ('Greater than y', 0))
) x (condition, value)
Then use that in your where clause...
select *
from Table
where not exists (select 1 from #conditions where value = 1)
Or you can join onto it. If you are comparing ints, you could cross join and say where #conditions.condition < yourTable.value.

dynamic sql count in a variable

This query works
select #V_COUNT =COUNT(1) from TAB1
But I want to pass the table as variable how to do that in sybase ?
i tried this but didnt work
select #V_COUNT ='COUNT(1) from ''||#TMP_TABLE_NAME||'''
select #LL_COUNT = CONVERT(numeric(30),#V_COUNT)
edit:
i did this
SELECT #V_COUNT ='SELECT COUNT(1) from '+ #TABLE_NAME
execute (#V_COUNT)
SELECT #LL_COUNT = 'SELECT convert(NUMERIC(6),'||#V_COUNT||')'
Implicit conversion from datatype 'VARCHAR' to 'NUMERIC' is not
allowed. Use the CONVERT function to run this query.
You need to execute that dynamic query, using:
CREATE TABLE #Count(x int)
SELECT #sSQL = "INSERT #Count SELECT COUNT(1) from "+ #TMP_TABLE_NAME
execute (#sSQL)
SELECT #V_COUNT = x from #Count
DROP TABLE #Count
SELECT #LL_COUNT = (SELECT convert(NUMERIC(30,4), #V_COUNT))
SELECT #LL_COUNT
where #TMP_TABLE_NAME might be SELECT #TMP_TABLE_NAME = 'tablename' is simple string which you don't need to execute or get result from.

Where clause concat with comma

I am trying to write what I thought would be a simple where clause. The FULLNAME string is formatted like this ("Doe, John"), hence the where clause and concat function.
Here is the query:
SELECT *
FROM table
WHERE concat(LAST_NM, ', ', FIRST_NM) = FULLNAME;
The query fails with the following error:
Error Executing Database Query. [Macromedia][SQLServer JDBC Driver]
[SQLServer]Incorrect syntax near ','.
Is your FullName something like "Doe, John"?
Is your FullName complete?
if not
SELECT *
FROM table
WHERE concat(LAST_NM, ', ', FIRST_NM) like ('%' + FULLNAME + '%')
Although I do not see anything wrong with your query, I would like to suggest a way to troubleshoot, by trying to find if it is a specific raw values that cause the concat function to break.
The idea is to iterate through the raws printing each one's values so you'll know which one (if at all) fails it, and it might be easier to take it from there to the next step.
--Copy your table data to a temporary table
--E.g.
SELECT *
into #table
FROM
(
select 'Doe' as LAST_NM , 'Jhon' as FIRST_NM
union
select 'Ryan' as LAST_NM , 'Jack' as FIRST_NM
union
select 'Dylan' as LAST_NM , 'Bob' as FIRST_NM
) a
--Iterate through the rows to see which one causes the issue
DECLARE #I INT = 1
DECLARE #TableCount INT = (select count(*) from #table)
DECLARE #FN varchar(100)
DECLARE #LN varchar(100)
WHILE #I <= #TableCount
BEGIN
SET #FN = (select Top 1 FIRST_NM from #table)
SET #LN = (select Top 1 LAST_NM from #table)
print(#I)
print(#FN)
print(#LN)
print('------------------')
delete top (1) from #table
SET #I = #I + 1
END