Execute dynamic SQL queries [closed] - sql-server

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I need to execute a SQL like bellow inside a SP.
DECLARE
#varSearchQ VARCHAR(100),
#varFieldName VARCHAR(100),
#varTableName VARCHAR(100),
#Sql VARCHAR(Max)
SET #varSearchQ='000'
SET #varFieldName='varConsoleID'
SET #varTableName='FF.ConsoleDT'
SET #Sql = N'SELECT ' + #varFieldName + '
FROM ' + #varTableName + '
WHERE ' + #varFieldName + ' LIKE %' + #varSearchQ + '%'
I found a way like EXEC sp_executesql #Sql. But I'm getting errors.

Try this
You Should Use Print for Debugging Statments
Create proc MYPROC
as
BEGIN
DECLARE
#varSearchQ VARCHAR(100),
#varFieldName VARCHAR(100),
#varTableName VARCHAR(100),
#Sql VARCHAR(Max)
SET #varSearchQ='000'
SET #varFieldName='varConsoleID'
SET #varTableName='FF.ConsoleDT'
SET #Sql = N'SELECT ' + #varFieldName + '
FROM ' + #varTableName + '
WHERE ' + #varFieldName + ' LIKE ''%' + #varSearchQ + '%'''
print (#Sql)
EXEC (#Sql)
END

Related

Stored Procedure in T-SQL [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I am trying to create a stored procedure for creating login into SQL Server. The stored procedure is complied successfully but I am getting error when I am executing the stored procedure.
CREATE OR ALTER PROCEDURE dbo.sp_login_1
(#userId varchar(15),
#passwd varchar(15),
#db varchar(15))
AS
BEGIN
DECLARE #stmt NVARCHAR(1000)
SET #stmt = 'CREATE LOGIN ' + #userId +
' WITH PASSWORD = ' + #passwd + ', ' +
' DEFAULT_DATABASE = ' + #db + '; ' +
'CREATE USER' + #userId +
' FROM LOGIN ' + #userId + ';' +
'ALTER ROLE groupAdmin ADD MEMBER' + #userId + ';'
EXEC sp_executesql #stmt;
END;
exec dbo.sp_login_1 #userId='user1', #passwd ='pwd', #db ='dbo.myDB';
The following error is displayed.
Msg 102, Level 15, State 1, Line 159
Incorrect syntax near 'pwd'.
Msg 102, Level 15, State 1, Line 159
Incorrect syntax near ';'.
You must add single quotes for the password field. Best to do this with QUOTENAME
SET #stmt = 'CREATE LOGIN ' + QUOTENAME(#userId) +
' WITH PASSWORD = ' + QUOTENAME(#passwd, '''') + ', ' +
' DEFAULT_DATABASE = ' + QUOTENAME(#db) + '; ' +
'CREATE USER' + QUOTENAME(#userId) +
' FROM LOGIN ' + QUOTENAME(#userId) + ';' +
'ALTER ROLE groupAdmin ADD MEMBER ' + QUOTENAME(#userId) + ';'
The reason the error message refers to pwd (which is not in the script) is because it clearly passed the pwd as a #passwd parameter.

Looking for Dynamic Stored Procedure, to use for multiple queries [duplicate]

This question already has an answer here:
THE CURSOR CURSOR NAME IS NOT IN A PREPARED STATE
(1 answer)
Closed 2 years ago.
I want to design a dynamic stored procedure, where I will be passing the column name, table name and my where clause. So that I can use the stored procedure to run select on different table with different parameters.
I'm not sure if this is possible. If yes, anyone will able to help me with example.
For example.
Query 1: Select name, number, total into out_name, out_number, out_total from student where total > 100;
Query 2: select book into out_book from lib where cost > 100;
I should able to execute above queries in single stored procedure by passing the column, table and where clause.
I created something like below. I did something like this for delete, delete working fine.
SET V_SELECT =
'SELECT ' || SELECT_FIELDS ||
' FROM ' || TABLE_NAME ||
' WHERE ' || WHERE_CLAUSE ||
' WITH UR';
EXECUTE IMMEDIATE V_SELECT INTO || INTO_FIELDS ||;
CREATE PROCEDURE usp_DynamicProc
(
#SelectFields NVARCHAR(1024)
, #IntoTableName NVARCHAR(255)
, #TableName NVARCHAR(255)
, #WhereClause NVARCHAR(1024)
)
AS
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'SELECT ' + #SelectFields + ISNULL(' INTO ' + #IntoTableName,'') + ' FROM ' + #TableName + ' WHERE ' + #WhereClause
EXEC sp_executesql #SQL

SQL server function how to use parameter to in query [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
my sql function is not working parameter value. If provide hard code value it will give me results.
ALTER function [dbo].[team_concat] (#input varchar)
returns varchar(8000)
as
BEGIN
declare #putout varchar(8000)
set #putout = null
-- select #putout = COALESCE(IsNull(#putout+ ', ', ''), '') + team_residence_location from programs where team_combo = 'Hartford CIS / Coaching'
select #putout = COALESCE(IsNull(#putout+ ', ', ''), '') + team_residence_location from programs where team_combo = #input
return #putout
Try this:
ALTER function [dbo].[team_concat] (#input varchar(100)) --- specify length
returns varchar(8000)
as
BEGIN
declare #putout varchar(8000)
set #putout = null
-- select #putout = COALESCE(IsNull(#putout+ ', ', ''), '') + team_residence_location from programs where team_combo = 'Hartford CIS / Coaching'
select #putout = COALESCE(IsNull(#putout+ ', ', ''), '') + team_residence_location from programs where team_combo = #input
return #putout

Is there a speed difference between using EXEC sp_executesql and direct SQL [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
If it was a big query would it be faster on the second stored procedure ?
CREATE PROCEDURE Customers_GetCustomer
#CustId CHAR(5),
#type int,
#search nvarchar
AS
BEGIN
DECLARE #SQL NVARCHAR(2000)
SET #SQL = 'SELECT ContactName FROM Customers WHERE CustomerId = '+CONVERT(nvarchar(20), #CustId)
if(#type = 1)
BEGIN
#SQL += 'AND NAME='+#search
END
if(#type = 2)
BEGIN
#SQL += 'AND ADDRESS='+#search
END
EXEC sp_executesql #SQL
END
Versus:
CREATE PROCEDURE Customers_GetCustomer
#CustId CHAR(5),
#type int,
#search nvarchar
AS
BEGIN
SELECT ContactName FROM Customers
WHERE CustomerId = #CustId
AND (NAME = #search OR #type <> 1)
AND (ADDRESS = #search OR #type <> 2)
END
What is the better choice between first and second?
With a simple query like this, there will be virtually no difference even at 1000s of executions/sec. (Based on my own testing when I had the same question.)
Assuming it's properly parameterised, a complex query will only have the additional overhead of hashing the longer string to match the execution cache.
But I'd suggest testing it yourself, with https://www.brentozar.com/archive/2015/05/how-to-fake-load-tests-with-sqlquerystress/ for example.

Incorrect Syntax near "=" in Dynamic SQL

Below is the query causing error:
EXECUTE (' UPDATE facetswrk.dbo.ODS_SUBSC_PREM_REPORT ' + ' SET ' + #lcrcolumn_name + ' = ' + #lcrcolumn_total)
Your syntax is ok, probably you have wrong valye for column name, or you need to cast #lcrcolumn_tot as nvarchar.
Give us the value for the variable, pr check by yourself with the flowing statement:
declare #lcrcolumn_name nvarchar(50) = 'blabla',
#lcrcolumn_tot nvarchar(50) = 10
declare #sql nvarchar(4000);
set #sql = ' UPDATE facetswrk.dbo.ODS_SUBSC_PREM_REPORT SET ' + #lcrcolumn_name + ' = ' + #lcrcolumn_tot
print #sql
execute(#sql)
Best is to print the dynamic sql before you execute it to understand what is causing the error, you may have some data value in #lcrcolumn_name and #lcrcolumn_total which may be creating the problem.

Resources