Insert string into SQL query as plain text in stored procedure - sql

I'm trying to write a stored procedure in SQL Server that checks if search input exists in a column.
SELECT *
FROM Product
WHERE #Type LIKE #SearchResult
My problem is that when I fetch #Type from user's input, it comes as a string in SQL therefore syntax is wrong and it returns NULL.
Is there a way to get rid off single quotations or convert it to plain text in SQL?
So if #Type is "ProductName" it would appear in SQL as
SELECT *
FROM Product
WHERE ProductName LIKE #SearchResult (no single quotes around `ProductName`)

You have to use dynamic SQL to replace anything other than a constant in a query:
DECLARE #sql NVARCHAR(MAX);
SET #SQL = 'SELECT * FROM Product WHERE #Type LIKE #SearchResult';
SET #SQL = REPLACE(#SQL, '#Type', #Type);
exec sp_executesql #sql,
N'#SearchResult NVARCHAR(MAX)',
#SearchResult=#SearchResult;
You can still pass the #SearchResult value using a parameter.

Related

OPENQUERY(SERVERNAME, STOREDPROCEDURE) Syntax error

This is my code
DECLARE #stringvariable nvarchar(200) = 'Hello';
DECLARE #sql nvarchar(2000) = SELECT * INTO ##global FROM OPENQUERY(DB1, ''EXEC GETCASE ''' + #stringvariable + ''''')'
Printing #sql returns a correctly formatted query, however SQL Server doesn't like #stringvariable and returns an error
Msg 102, Level 15, State 1, Line 11
Incorrect syntax near 'Hello'.
Here is what the outputted query looks like
SELECT * INTO ##global FROM OPENQUERY(DB1, 'EXEC GETCASE 'Hello'')
How can I avoid this error? It seems like because my stored procedure takes a string parameter, it's throwing off the query. I've read that OPENQUERY does not support variables, but I've parameter the variable so it should work?
Appreciate your help!
The stored procedure exists in a database and a schema. You need to supply those. Supposing database db_name and schema schema_name:
DECLARE #stringvariable nvarchar(200) = 'Hello';
SET #stringvariable=REPLACE(#stringvariable,'''',''''''''''); -- doubly doubled single quotes for the dynamic statement
DECLARE #sql nvarchar(2000) = 'SELECT * INTO ##global FROM OPENQUERY(DB1, ''SET FMTONLY OFF;EXEC db_name.schema_name.GETCASE ''''' + #stringvariable + ''''''')';
I've also made sure single quotes are properly escaped in the #stringvariable.
It's also likely you need to start the query with SET FMTONLY OFF; so I've added that.
Update: To test this I created following simple procedure on a linked server local_server in database TEST_TT
CREATE PROCEDURE [dbo].[tst]
#i VARCHAR(128)
AS
SELECT #i AS field;
I then ran the following:
DECLARE #var VARCHAR(128)='TT.';
SET #var=REPLACE(#var,'''',''''''''''); -- doubly doubled single quotes for the dynamic statement
DECLARE #stmt VARCHAR(4000)='SELECT * INTO ##tt FROM OPENQUERY(local_server,''SET FMTONLY OFF;EXEC TEST_TT.dbo.tst '''''+#var+''''''');';
EXEC (#stmt);
SELECT * FROM ##tt;
DROP TABLE ##tt;
And I received the results. I count 7 (!!) single quotes at the end of the query... yuck! Updated original part with the same number of quotes.

SQL Server stored procedure passing parameters into variables

I have a big query which works and I want to write a stored procedure for it.
I'm getting this error:
the OLE DB provider SQLNCLI11" for linked server "theServer" does not contain the table ""#dbName"."dbo"."tableName"
What I am trying to do:
create PROCEDURE [sys.sp_myProcedure]
(
#dbName varchar(30) output,
#rid varchar (10) output,
#mdate output
)
AS
BEGIN
declare #prt varchar(12)
declare #pid int
declare #cid int
--declare #rid int
declare #aid int
SET NOCOUNT ON;
set #cid= (select CID from theServer.[#dbName].dbo.tableName where RID= #rid)
set #pid= (select PID from theServer.[#dbName].dbo.tableName where RID= #rid)
set #aid= (select aid from theServer.[#dbName].dbo.tableName where RID= #rid)
--then my query begins
theServer.[#dbName].dbo.tablename is a linked server.
What I want to do is:
execute [sys.sp_myProcedure] 'someDbname', '123', '2012-03-03'
and the parameters passed here would set/update the variables #dbName, #rid, #mdate at runtime. ( #mdate I have it further away in the query, it's too big to adapt it with myTable and to change all the sensitive data).
How can I do this ?? (using SQL Server 2012)
edit (based on the comments and answers):
so, it's #thatString = '--insert the query here ' . Then, in my case how can i set those variables according to the parameters inside the query? Should i do it with replace? like this: set #thatString= replace(#thatString, dbName, #dbname) ?
**
edit 2
**
set #sql = '
use [someDbName];
use [123];
use [2012-03-03];
select ... '
set #sql = replace (#sql, 'someDbName', #dbName)
set #sql = replace (#sql, '123', #rid)
set #sql = replace (#sql, '2012-03-03', #mdate)
execute #sql
end
Did i get it right? is the execute #sql in the right place?
I'm asking cause it doesnt work. i'm getting the name ' --part of my query here' is not a valid identifier
Names of databases or other objects cannot be specified dynamically from variables. The workaround is to compose a dynamic SQL query in a string, into which you concatenate the required names, and then execute (#thatString).
(You might think you can employ use, but it is scoped such that you would have to include the rest of your query within the same executed string.)
--
Edit with more info as requested. You can compose the string however you like. If you need any more guidance, there are plenty of pages that discuss dynamic T-SQL. But hey, two ideas:
set #myDynamicQuery =
'
use [' + #myDynamicDatabase + '];
select BLAH from WHOM where DATA = ''what'';
';
or if you will be using the name a lot, you could reduce the hassle caused by breaking in and out of single quotes as follows - though I personally never use this as I don't like how it looks:
set #myDynamicQuery =
'
use [A_RARE_PLACEHOLDER];
select BLAH from WHOM where DATA = ''what'';
-- lots more uses of A_RARE_PLACEHOLDER
';
set #myDynamicQuery = replace(
#myDynamicQuery,
'A_RARE_PLACEHOLDER',
#myDynamicDatabase
);
Then execute (#myDynamicQuery);

SQL SELECT results INTO temp table using query string

I am trying to write some dynamic SQL queries that select results into a temp table with a query string. It looks like follows:
DECLARE #SQL Varchar(4000)
SET #SQL = 'SELECT * INTO #tmp_tab FROM dbo.sometable'
EXEC(#SQL)
It doesn't give any error to run the code, but when I want to select from #tmp_tab, it says the table doesn't exist.
So I am wondering if there is any special syntax for it, or dynamic SQL doesn't support such operation?
Many thanks.
Maybe it has something to do with access. If you create a global temp table, it will work.
DECLARE #SQL Varchar(4000)
SET #SQL = 'SELECT * INTO ##tmp_tab FROM dbo.batch'
EXEC(#SQL)
SELECT * FROM ##tmp_tab

Store result of dynamic SQL generating XML to XML Variable

So I have found plenty of examples across SO that show how to assign the result of dynamic SQL to variables but I have yet to find one that does it the way that I am trying to... So either I am going about this the wrong way or I just haven't found the proper syntax to perform this correctly.
Basically, I am trying to create an XML record of a row from a table before deleting the row from the table (think of it as an audit of the table) using a Stored Procedure. I was attempting to do this through dynamic SQL so that the Stored Procedure can be called from multiple other Stored Procedures that perform Delete operations on their corresponding tables, but before doing so they pass the necessary information (the #sql variable which will contain the select statement to obtain the record) to this Audit Stored Procedure.
Create Procedure dbo.AuditDelete(
#sql NVARCHAR(200),
#TableName VARCHAR(50),
#UserName NVARCHAR(256)
)
AS
DECLARE #XML XML
BEGIN
--at this point #sql will contain a select statement written by the calling stored procedure
--which is specifically written to return the record that is being deleted, example:
#sql = select * from my.table where tableId = 1 FOR XML AUTO
execute sp_executesql #sql, N'#XML XML OUTPUT', #XML = XML OUTPUT;
SELECT #XML
--I was doing this as a check to ensure that XML has the record
--because the execute command returned the XML record, but #XML is null...
--and I can't figure out why
--code for inserting into the Audit table
So I'm sure that its either some syntax I'm missing or perhaps I'm just going about this the wrong way. Any suggestions?
Note: this is being done in SSMS on SQL Server 2008 R2
You need to assign the result your query to the parameter in the dynamic SQL.
set #sql = N'set #XML = (select * from my.table where tableId = 1 FOR XML AUTO)'
execute sp_executesql #sql, N'#XML XML OUTPUT', #XML OUTPUT

Is it possible to execute a sql statement containing variable?

Is it possible to execute a sql statement containing variable?
DECLARE #SCHEMA varchar(40)
set #SCHEMA='X_SLF'
select * from #SCHEMA..Acc_tblCompany --// anyway to use this type of statement?
--below statement works
select * from X_SLF..Acc_tblCompany
--I don't want to do this following solution:
DECLARE #Sql nvarchar(80)
set #Sql=' select * from '+#SCHEMA+'..Acc_tblCompany'
Execute sp_executesql #Sql
Perhaps you could implement this as a case statement. It's not quite what you're asking for, but at least you can create the illusion to the caller that it's parameterized wrt schema