I am totally confused with this procedure.please correct my mistakes in quotes.
create procedure queryingsfor
#Tabname nvarchar(250),
#colname nvarchar(250),
#opname nvarchar(290),
#valuesname nvarchar(239)
as
begin
set NOCOUNT on;
declare #sql varchar(4000)
set #sql='select * from' +#Tabname+ 'where' +#colname+''''+#opname+''''+ ''''+#valuesname+''''
exec(#sql)
end
exec queryingsfor 'education','eduCurrentStudy','=','DME'
I'm only getting:
Error: Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'fromeducationwhereeduCurrentStudy'.
You might want to add some spaces in there
set #sql='select * from ' +#Tabname+ ' where '
+#colname+''''+#opname+''''+ ''''+#valuesname+''''
The correct statement would be something like
set #sql='select * from ' +#Tabname+ ' where '
+#colname + #opname+ ''''+#valuesname+''''
Or
even better
set #sql='select * from [' +#Tabname+ '] where
[' +#colname + ']' + #opname+ ''''+#valuesname+''''
To protect you from SQL injection you should do like this instead.
alter procedure queryingsfor
#Tabname nvarchar(250),
#colname nvarchar(250),
#opname nvarchar(4),
#valuesname nvarchar(239)
as
begin
set NOCOUNT on;
declare #sql nvarchar(4000)
set #sql = 'select * from '+quotename(#Tabname)+ ' where ' +quotename(#colname)+#opname+'#valuesname'
exec sp_executesql #sql, N'#valuesname nvarchar(239)', #valuesname
end
Related
I have several tables having the same structure. The tables are named by year that is 2001,2002 and so on. I am in need to search a column for a value in each table and get the count for each table.
I have created a stored procedure below but I keep getting an error
Invalid column 'lol'
This is the stored procedure used:
CREATE PROCEDURE [dbo].[CountSP]
#TableName NVARCHAR(128),
#SearchParam NVARCHAR(50),
#SearchInput NVARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'SELECT COUNT('+QUOTENAME(#SearchParam)+') FROM ' + QUOTENAME(#TableName) +'WHERE'+QUOTENAME(#SearchParam)+'LIKE '+QUOTENAME(#SearchInput)+
+ N' SELECT * FROM '+QUOTENAME(#TableName)
EXECUTE sp_executesql #Sql
END
Executing it:
DECLARE #return_value INT
EXEC #return_value = [dbo].[CountSP]
#TableName = N'1999',
#SearchParam = N'USERDESC',
#SearchInput = N'lol'
SELECT 'Return Value' = #return_value
I don't know why you are using LIKE operator there while you don't use wildcards, also use SysName datatype directly for object names.
Create PROCEDURE [dbo].[CountSP]
(
#TableName SysName,
#SearchInput NVARCHAR(50),
#SearchParam SysName
)
AS
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX) = N'SELECT COUNT(' +
QUOTENAME(#SearchParam) +
N') FROM ' +
QUOTENAME(#TableName) +
N' WHERE ' +
QUOTENAME(#SearchParam) +
N' = ' + --You can change it to LIKE if needed
QUOTENAME(#SearchInput, '''') +
N';';
-- There is no benifits of using LIKE operator there
EXEC sp_executesql #SQL;
Then you can call it as
EXEC [dbo].[CountSP] N'YourTableNameHere', N'SearchInput', N'ColumnName';
This is because it is currently translated to :
SELECT COUNT([USERDESC]) FROM [1999] WHERE [USERDESC] LIKE [lol]
this means that it is comparing the "USERDESC" column with the "lol" column but from what I am understanding lol isn't a column but a value? which means you should lose the QUOTENAME for that variable.
See the documentation here : https://learn.microsoft.com/en-us/sql/t-sql/functions/quotename-transact-sql?view=sql-server-2017
You need to pass your parameter #SearchInput as a parameter to sp_execute:
CREATE PROCEDURE [dbo].[CountSP] #TableName sysname, --This is effectively the same datatype (as sysname is a synonym for nvarchar(128))
#SearchParam sysname, --Have changed this one though
#SearchInput nvarchar(200)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql nvarchar(MAX);
SET #Sql = N'SELECT COUNT(' + QUOTENAME(#SearchParam) + N') FROM ' + QUOTENAME(#TableName) + N'WHERE' + QUOTENAME(#SearchParam) + N' LIKE #SearchInput;' + NCHAR(13) + NCHAR(10) +
N'SELECT * FROM ' + QUOTENAME(#TableName);
EXECUTE sp_executesql #SQL, N'#SearchInput nvarchar(200)', #SearchInput;
END;
QUOTENAME, by default, will quote a value in brackets ([]). It does accept a second parameter which can be used to define a different character (for example QUOTENAME(#Value,'()') will wrap the value in parentheses). For what you want though, you want to parametrise the value, not inject (a quoted) value.
I use dynamic sql to create database an tables
this is sql script
DECLARE #DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +#DatabaseName+']');
EXECUTE('USE ' + #DatabaseName)
GO
CREATE SCHEMA [Framework]
GO
the error I get
Msg 2714, Level 16, State 6, Line 1
There is already an object named 'Framework' in the database.
Msg 2759, Level 16, State 0, Line 1
CREATE SCHEMA failed due to previous errors
.
this error because EXECUTE('USE ' + #DatabaseName) not work
I try to use
SET #SQL02 = 'USE ['+ convert(nvarchar(50),#DatabaseName) +']; SELECT DB_NAME();'
exec sp_executesql #SQL02
but not work
what I can do?
DECLARE #Query VARCHAR(200);
SET #Query = CONCAT('USE ', QUOTENAME('<MyDatabase>'), '; ', 'select DB_NAME();');
EXECUTE (#Query);
This will return <MyDatabase> as long as you remain within one EXECUTE.
I prefer this form for remote execution:
declare #sql nvarchar(max) = N'select Db_Name()';
<DatabaseName>.sys.sp_executesql #sql;
You can put this logic into a more convenient form by making into a stored procedure:
create procedure dbo.usp_ExecuteSqlCommand (
#databaseName sysname
, #sqlCommand nvarchar(max)
)
as
begin;
set nocount on;
set xact_abort on;
declare #innerStatement nvarchar(max) = #sqlCommand;
declare #outerStatement nvarchar(max);
set #databaseName = QuoteName(ParseName(#databaseName, 1), N'[');
set #outerStatement = #databaseName + N'.sys.sp_executesql #stmt = #innerStatement;';
execute sys.sp_executesql
#stmt = #outerStatement
, #params = N'#innerStatement nvarchar(max)'
, #innerStatement = #innerStatement;
end;
Usage is obvious:
execute dbo.usp_ExecuteSqlCommand
#databaseName = N'master'
, #sqlCommand = N'select Db_Name();';
Try this:(if you use execute, the db context will change only for that execute only)
DECLARE #DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +#DatabaseName+']');
use [test]
go
CREATE SCHEMA [Framework]
GO
dECLARE #LS_SQL CHAR(100)
dECLARE #SQL varCHAR(max)
SET #LS_SQL=ltrim('''STOCK IN HAND'',''STORE'',''PRODUCT''')
set #SQL='SELECT * FROM ITEM WHERE GROUPNAME IN(' + rtrim(#LS_SQL) + ')'
PRINT #SQL
execute #SQL
result
SELECT * FROM ITEM WHERE GROUPNAME IN('STOCK IN
HAND','STORE','PRODUCT') Msg 2812, Level 16, State 62, Line 9 Could
not find stored procedure 'SELECT * FROM ITEM WHERE GROUPNAME
IN('STOCK IN HAND','STORE','PRODUCT')'.
This command
execute #SQL
run a procedure. If you wan to run dynamic sql you should use below command:
exec (#SQL)
you can also use
execute sp_sqlexec #SQL
I suggest to use sp_executesql, like:
exec sp_executesql #stmt = #SQL
you can see more help here Dynamic SQL - EXEC(#SQL) versus EXEC SP_EXECUTESQL(#SQL)
try this
dECLARE #LS_SQL CHAR(100)
dECLARE #SQL varCHAR(max)
SET #LS_SQL=ltrim('''STOCK IN HAND'',''STORE'',''PRODUCT''')
set #SQL='SELECT * FROM ITEM WHERE GROUPNAME IN(' + rtrim(#LS_SQL) + ')'
PRINT #SQL
execute sp_sqlexec #SQL
I have this SQL code that I'm using to insert 3 tables at a time dynamically. When I try to run it, I get this message
Msg 137, Level 16, State 1, Procedure InsertData, Line 28
Must declare the scalar variable "#RECEIVABLESDATA".
Any ideas?
USE [PantaRei]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertData]
#RECEIVABLESDATA RECEIVABLESTABLE READONLY,
#DILUTIONSDATA DILUTIONSTABLE READONLY,
#ACCOUNTABLESDATA ACCOUNTABLESTABLE READONLY,
#TABLE1 VARCHAR(MAX),
#TABLE2 VARCHAR(MAX),
#TABLE3 VARCHAR(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
DECLARE #CMD nvarchar(345)
SET NOCOUNT ON;
SET #TABLE1 = RTRIM(#TABLE1)
SET #TABLE2 = RTRIM(#TABLE2)
SET #TABLE3 = RTRIM(#TABLE3)
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE1) +
'SELECT * FROM [DBO].' + QUOTENAME(#RECEIVABLESDATA)
EXECUTE sp_executesql #CMD
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE2) +
'SELECT * FROM [DBO].' + QUOTENAME(#DILUTIONSDATA)
EXECUTE sp_executesql #CMD
SET #CMD =
'INSERT INTO '+ QUOTENAME(#TABLE3) +
'SELECT * FROM [DBO].' + QUOTENAME(#ACCOUNTABLESDATA)
END
Try to use temp tables:
SELECT * INTO #t1 FROM #RECEIVABLESDATA;
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE1) +
'SELECT * FROM #t1';
EXECUTE sp_executesql #CMD
Also here is the other way. Check if it works in your MS SQL version:
SET #CMD =
'INSERT INTO ' + QUOTENAME(#TABLE1) +
'SELECT * FROM #RECEIVABLESDATA';
EXECUTE sp_executesql #CMD, N'#RECEIVABLESDATA RECEIVABLESDATA READONLY', #RECEIVABLESDATA;
I have a dynamic query which reads like this
Alter PROCEDURE dbo.mySP
-- Add the parameters for the stored procedure here
(
#DBName varchar(50),
#tblName varchar(50)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare #string as varchar(50)
declare #string1 as varchar(50)
set #string1 = '[' + #DBName + ']' + '.[dbo].' + '[' + #tblName + ']'
set #string = 'select * from ' + #string1
exec #string
END
I am calling like this
dbo.mySP 'dbtest1','tblTest'
And I am experiencing an error
"Msg 203, Level 16, State 2, Procedure mySP, Line 27
The name 'select * from [dbtest1].[dbo].[tblTest]' is not a valid identifier."
What is wrong? and How to overcome?
Thanks in advance
It thinks that the contents of #string refer to a stored procedure name. You need to put
EXEC (#string)
or better use the stored procedure sp_executesql
You should also set up some guard code to check that the values you are passing in are the names of real tables and databases. You can query the views in the INFORMATION_SCHEMA to validate the input.
You can read more on safer dynamic SQL on my blog.
Change
exec #string
To
exec(#string)
Here's a working SP I just tested:
CREATE PROCEDURE [dbo].[test]
#DBName varchar(50),
#tblName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #string AS VARCHAR(50)
DECLARE #string1 AS VARCHAR(50)
SET #string1 = '[' + #DBName + '].[dbo].[' + #tblName + ']'
SET #string = 'select * from ' + #string1
EXEC(#string)
END
if you use EXEC as:
EXEC #String
it is trying to run a procedure with the name contained within the #String variable. try it out:
create procedure TestProc
as
print 'you called TestProc!'
go
declare #string varchar(20)
set #string='TestProc'
exec #string
if you use EXEC as:
EXEC (#Query)
you run the sql within the #Query variable, try it out:
DECLARE #Query varchar(50)
set #Query='Print ''just ran it!'''
EXEC (#Query)
ALTER PROCEDURE test_sp
-- Add the parameters for the stored procedure here
(
#DBName varchar(50),
#tblName varchar(50)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Insert statements for procedure here
declare #string as varchar(100)
declare #string1 as varchar(50)
set #string1 = '[' + #DBName + ']' + '.[dbo].' + '[' + #tblName + ']'
Print #string1
set #string = 'select * from' + #string1
Print #string
exec (#string)
SET NOCOUNT OFF
END