No output when stored procedure is executed - sql

No output when stored procedure is executed. The select statement works when I create a new query , but does not return any values when calling the store procedure within my Web app.

You want a dynamic sql.
try this.
Declare #strSQL nvarchar(2000)
set #strSQL = 'SELECT * FROM investor WHERE ' + #search_by + ' = ''' + #col + ''''
execute sp_executesql #strSQL

Related

Passing output from dynamic SQL

Currently I have a working version of a dynamic SQL query without any variables except one (#ColumnHeader). And am able to get the desired result being a collection of column names in one line separated by comma.
select #ColumnHeader = COALESCE(#ColumnHeader+',','') + '''' + column_name + ''''
from databaseName.Information_Schema.Columns
where table_name = 'Dates'
I am trying to add variables for Database_information_schema and TableName.
DECLARE #ColumnHeader varchar(8000)
DECLARE #Database_Information_SchemaColumns varchar(8000) = 'DatabaseName2.Information_Schema.Columns'
DECLARE #TableName varchar(8000) = 'dates'
DECLARE #sqlQuery as nvarchar(max) = 'Select ' + #ColumnHeader + '= COALESCE(' + #ColumnHeader+ +''','','''')+ ''''''''+column_name+'''''''' from ' + #Database_Information_SchemaColumns + 'where table_name = '''+ #TableName + ''''
Print #sqlQuery
EXEC sp_executesql #sqlQuery;
I am getting Null values and am not sure whats wrong here.
What follows is some working code. I explain the changes required:
You are trying to assign a parameter using dynamic SQL, therefore the parameter needs to be part of the dynamic SQL string, not concatenated with it.
To assign a parameter using dynamic SQL you have to pass it in/out of sp_executesql because the context the dynamic SQL is running under cannot see the parameters declared.
While this is not necessary, I have renamed the internal parameter so that its clear which parameter belongs in which scope. However both could use the same name if desired.
You were missing a space before your where.
I recommend using varchar(max) and nvarchar(max) as there is no need to risk running into the 8k limit.
Use quotename for any database, schema, table or column names to protect against injection.
Use the sysname datatype where a system name is being stored
Split all system names into parts to allow the use of quotename
DECLARE #ColumnHeader varchar(max)
, #Database_Information_Database sysname = 'DatabaseName2'
, #Database_Information_Schema sysname = 'Information_Schema'
, #Database_Information_Columns sysname = 'Columns'
, #TableName sysname = 'dates';
DECLARE #sqlQuery nvarchar(max) = 'select #ColumnHeaderInteral = COALESCE(#ColumnHeaderInteral,'','','''') + '''''''' + column_name + '''''''' from '
+ quotename(#Database_Information_Database) + '.'
+ quotename(#Database_Information_Schema) + '.'
+ quotename(#Database_Information_Columns)
+ ' where quotename(table_name) = ''' + quotename(#TableName) + '''';
PRINT #sqlQuery;
EXEC sp_executesql #sqlQuery, N'#ColumnHeaderInteral varchar(max) output', #ColumnHeaderInteral = #ColumnHeader out;
SELECT #ColumnHeader;
Official Documentation

Pass the Multiple quotes around #variable wherever single quote is there

Below is my procedure. It is working fine.
Create PROCEDURE [dbo].[spCompanyName]
(
#CompanyName VARCHAR(100))
AS
Begin
DECLARE #sql VARCHAR(MAX)
SET #sql = ' Select EmpID,CompanyName FROM Employee' + CHAR(13) + CHAR(10)
IF len(#CompanyName) > 0
BEGIN
SET #sql = #sql + ' Where (RTRIM(LTRIM(CompanyName)) like ''' + #CompanyName + '%'') ' + char(13) + char(10)
END
PRINT #SQL
EXEC(#sql)
End
exec spCompanyName #CompanyName='So Unique, formerly Sofia''''s'
I need Wherever single quote is there in companyname,if I pass 8 quotes in single quotes I need output.above procedure where do I need to change.
Eg:
exec spCompanyName #CompanyName='So Unique, formerly Sofia''''''''s'
exec spCompanyName #CompanyName='Absolute''''''''s,Strategy''''''''s'
Don't think "I'll throw away all of the useful features of using parameters to separate data from code and start manually trying to protect strings" - keep using parameters.
Rather than
EXEC(#sql)
Have:
EXEC sp_executesql #sql,N'#CompanyName varchar(100)',#CompanyName = #CompanyName
And change:
SET #sql = #sql + ' Where (RTRIM(LTRIM(CompanyName)) like ''' + #CompanyName + '%'') ' + char(13) + char(10)
to:
SET #sql = #sql + ' Where (RTRIM(LTRIM(CompanyName)) like #CompanyName + ''%'') ' + char(13) + char(10)
Or, in the alternative, consider just writing a normal query, no dynamic SQL:
Create PROCEDURE [dbo].[spCompanyName]
(
#CompanyName VARCHAR(100))
WITH RECOMPILE
AS
Begin
Select EmpID,CompanyName FROM Employee
Where RTRIM(LTRIM(CompanyName)) like #CompanyName + '%' or
#CompanyName is null
End
Assuming you're using SQL Server 2008 (with particular patch levels) or later, as specified in Erland Sommarskog's Dynamic Search Conditions in T-SQL
If you are going to create a new stored procedure for this feature then you can have this in much better way then dynamic.
You should execute different select queries based on if CompanyName is passed or not.
You can simply the stored procedure as following.
Create PROCEDURE [dbo].[spCompanyName]
(
#CompanyName VARCHAR(100))
AS
Begin
IF LEN(#CompanyName) > 0
BEGIN
Select EmpID,CompanyName FROM Employee WHERE RTRIM(LTRIM(CompanyName)) like '' + #CompanyName + '%'
END
ELSE
BEGIN
Select EmpID,CompanyName FROM Employee
END
END
I am not sure why you need to pass so many single quotes in the parameter value but to me it looks like you can execute the procedure with following simple way.
EXEC spCompanyName #CompanyName='So Unique, formerly Sofia''s'
EXEC spCompanyName #CompanyName='Absolute''s,Strategy''s'
This should help you finding your solution.

Dynamic SQL in SQL Server

I have a SQL CLR stored procedure dbo.Parallel_AddSql that takes a SQL query to execute as a string parameter.
It looks something like this :
exec dbo.Parallel_AddSql 'sql1',
'insert into test.dbo.table_1 values (1, ''test1'')'
I need to pass my SQL query as dynamic SQL statement to Parallel_AddSql procedure.
SQL statement that I need to pass is procedure execution statement with parameters i.e
Exec dbo.MatchLastName #LastNameFromUser = #LastName,
#checkbool = #checkbool
How do I pass this? As #lastName and #checkbool will be out of scope if I pass them as such in the string.
I tried using this :
set #SQL = 'Exec dbo.MatchFirstName #FirstNameFromUser =' + #firstname + ',
#checkbool = ' + cast(#checkbool as nvarchar(10))
exec dbo.Parallel_AddSql 'sql1', #SQL
However, I get this error :
Could not find stored procedure 'dbo.MatchFirstName'
dbo.MatchFirstName is there but dbo.Parallel_AddSql is not able to see it at all.
dbo.Parallel_AddSql is coming the library code given here
Edit : Unclosed quotation mark error :
set #SQL = 'Exec dbo.MatchFirstName #FirstNameFromUser =''' + #firstname
+ ''', #checkbool = ''' + cast(#checkbool as nvarchar(10))
set #SQL = 'Exec dbo.MatchFirstName #FirstNameFromUser =''' + #firstname + ''', ...'
If you were to call the stored procure in a script, you'd write Exec dbo.MatchFirstName #FirstNameFromUser = 'John', not Exec dbo.MatchFirstName #FirstNameFromUser = John, right? Same thing with your dynamic SQL. You have to add in the quotes.
If you want to keep the #FirstName = #FirstName syntax, you'll have to declare and set your variables in the string itself. So,
'DECLARE #FirstName Varchar(Max); SET #FirstName = ''John''; EXEC ...'
EDIT
If you look at the example they gave for Parallel_AddSql, they used the fully qualified name of the procedure.
The example from www.codeproject.com:
exec ClrLibDb.dbo.Parallel_AddSql 'sql1', 'insert into test.dbo.table_1 values (1, ''test1'')'
I think it requires the database to be part of that. So, YourDbName.dbo.MatchFirstName. It may be looking at master for your stored procedure, which is why it's not finding it.

SQL Server stored procedures calls require variable declaration (but already declared)

I have a few stored procedures which I call in this order.
So, from the first stored procedure, importTaxonomy I call parseXBRL and from parseXBRL I call createTaxonomyStructure.
But in this flow, when the code of the last stored procedure is executed I get an error.
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "#temporaryTable".
Below you can find the first few lines code of this stored procedure:
CREATE PROCEDURE createTaxonomyStructure #taxonomy_table nvarchar(max), #debug bit = 0
AS
DECLARE #statement NVARCHAR(MAX)
DECLARE #temporaryTable TABLE (taxonomyLine NVARCHAR(MAX)) -- declared a temporary table to avoid creating a Dynamic Query with the entire cursor, but just with the temporary table
DECLARE #taxonomyLine NVARCHAR(MAX) -- variable that will store one line of the taxonomy
SET #statement = 'INSERT INTO #temporaryTable SELECT taxText FROM ' + #taxonomy_table -- statement that will import the taxonomy in the temporary table
EXEC sp_executesql #statement
DECLARE taxonomyCursor CURSOR READ_ONLY FAST_FORWARD FOR -- read each line in the taxonomy to parse afterwards
SELECT taxonomyLine
FROM #temporaryTable
OPEN taxonomyCursor
FETCH NEXT FROM taxonomyCursor INTO #taxonomyLine -- parsing each taxonomy line and extracting the values from important attributes
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #id_element NVARCHAR(MAX)
DECLARE #leaf_element NVARCHAR(MAX)
SELECT #id_element = (SELECT dbo.extract_IDElement(#taxonomyLine))
SELECT #leaf_element = (SELECT dbo.extract_IDLeafElement(#taxonomyLine))
SET #statement = 'UPDATE ' + #taxonomy_table + ' SET fullName = ''' + #id_element + ''', leafName = ''' + #leaf_element + '''';
EXEC sp_executesql #statement
END
I do declare this variable, but I still get the error and I don't understand why.
How can I get over this error?
Thanks!
the error is here:
SET #statement = 'INSERT INTO #temporaryTable SELECT taxText FROM ' + #taxonomy_table -- statement that will import the taxonomy in the temporary table
EXEC sp_executesql #statement
change it to
set #statement = 'select taxText from ' + #taxonomy_table
insert into #temporaryTable
exec sp_executesql #statement
The error is happening because in the scope of executing #statement there's no variable table #temporaryTable.

SQL dynamically create stored procedures?

I am trying to create a script to create/setup a group of stored procedures that will all be fairly similar.
So I am trying to loop through this code, changing the #DATABASE_NAME and #TableName when needed.
/* Start loop */
DECLARE #create_stored_procedure nvarchar(max)
SET #create_stored_procedure = N'
USE [' + #DATABASE_NAME + ']
CREATE PROCEDURE [dbo].[sproc_imp_' + #TableName + ']
AS
BEGIN
PRINT(''doing something'')
END'
EXEC sp_executesql #statement = #create_stored_procedure
/* End loop */
But I am getting errors saying
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
or
'CREATE/ALTER PROCEDURE' does not allow specifying the database name as a prefix to the object name.
All the solutions online suggest using GO, but that won't work in dynamic SQL.
Does anyone know a possible solution for SQL Server 2005?
I wouldn't call the solution intuitive, but apparently this works. I prefer the look of this one though.
Try with spiting USe DB and create procedure. Like this
DECLARE #create_store_procedure nvarchar(max)
SET #create_store_procedure = N'
USE [' + #DATABASE_NAME + '] '
EXEC sp_executesql #statement = #create_store_procedure
SET #create_store_procedure = N'
CREATE PROCEDURE [dbo].[sproc_imp_' + #TableName + ']
AS
BEGIN
PRINT(''doing something'')
END '
EXEC sp_executesql #statement = #create_store_procedure
This is working perfectly for me
I tried Nithesh's answer and that didn't work for me it ended up creating the store procedure in the master table. Zec's answer worked. Creating a dynamic query inside my dynamic query.
DECLARE #create_store_procedure nvarchar(max)
DECLARE #use_db nvarchar(max)
SET #create_store_procedure = N'
CREATE PROCEDURE [dbo].[sproc_imp_' + #TableName + ']
AS
BEGIN
PRINT(''doing something'')
END '
SET #use_db = N'
USE [' + #DATABASE_NAME + ']
DECLARE #sub_create_store_procedure nvarchar(max)
SET #sub_create_store_procedure = ''' + REPLACE(#create_store_procedure, CHAR(39), CHAR(39) + CHAR(39)) + '''
EXEC sp_executesql #statement = #sub_create_store_procedure
'
EXEC sp_executesql #statement = #use_db