in operator issue in sql server - sql

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

Related

OPENQUERY query stored in string fails with EXEC

I'm trying to pull back some data via a linked server that has 'Geography' fields present, consequntly I'm trying to use Open Query.
I'm also trying to pass in a variable...
Can anyone explain this:
This is my sql...
DECLARE #Sql VARCHAR(200)
DECLARE #tnum VARCHAR(20)= 'abc';
SET #Sql = 'SELECT * FROM NationalPolygon.dbo.Polygon WHERE TitleNumber = ''''' + #tnum + '''''';
SET #Sql = 'SELECT * FROM OPENQUERY(mylinkedserver01, ''' + REPLACE(#Sql, '?', '''') + ''')'
SELECT #Sql;
EXEC #Sql;
If I select #Sql and run it, it works.
If I run the #Sql via EXEC it fails with:
Database 'SELECT * FROM OPENQUERY(mylinkedserver01, 'SELECT * FROM NationalPolygon' does not exist. Make sure that the name is entered correctly.
Thanks
C
You need to surround #Sql with brackets
EXEC (#Sql);

Stored procedure to Linked server with parameters - Error

I'm trying to create stored procedure to Linked server, which input parameter #ServerName is the name of Linked Server i use.
In this procedure I also Declare parameter which value I want to get from Dynamic SQL Query and line.
CREATE PROC sp_Version #ServerName varchar(30)
as
Declare #Ver varchar(10)
exec ('select #Ver from openquery(' + #ServerName + ', ''SELECT SUBSTRING (##VERSION, 22, 7) = #Ver''')
When I execute my sp i get an error saying:
"Must declare the scalar variable "#Ver"."
Could you please help me?
I'm not sure what your aim is with the value of #Ver, perhaps an OUTPUT parameter? If so, then the syntax would be:
CREATE PROC GetVersion #ServerName varchar(30), #Ver nvarchar(500) OUTPUT AS
DECLARE #SQL nvarchar(MAX);
SET #SQL = N'SELECT #dVer = Version' + NCHAR(10) +
N'FROM OPENROWSET(''SQLNCLI'',' + NCHAR(10) +
N' ' + QUOTENAME('Server=' + #ServerName + ';Trusted_Connection=YES;','''') + ',' +NCHAR(10) +
N' ''SELECT ##VERSION AS Version'');';
PRINT #SQL;
EXEC sp_executesql #SQL, N'#dVer nvarchar(500) OUTPUT', #dVer = #Ver OUTPUT;
GO
DECLARE #ver varchar(500)
EXEC GetVersion 'YourServerName', #ver OUTPUT;
PRINT #ver;
GO
DROP PROC GetVersion;
Note, firstly, as suggested I didn't use the sp_ prefix. I've also used sp_executesql instead of simply EXEC (this is generally better practice, as you can parametrise your dynamic SQL then, as i have done), and QUOTENAME to try and avoid injection.
I have come across this situation a couple of times. Try this:
CREATE PROC sp_Version #ServerName varchar(30)
as
Declare #Ver varchar(10)
DECLARE #SqlCommand nvarchar(MAX)
SET #SqlCommand = 'SELECT #Ver2 = SUBSTRING (##VERSION, 22, 7) '
DECLARE #sp_executesql VARCHAR(100)
SET #sp_executesql = #ServerName + '.master.sys.sp_executesql'
EXEC #sp_executesql #SqlCommand, N'#Ver2 nvarchar(10) out', #Ver out
SELECT #Ver

Dynamic SQL "USE [DB]" not worked

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

SQL Server Dynamic SQL Execution

I have a dynamic SQL query
DECLARE #ItemAreaCode NVARCHAR(MAX) = 'A062',
#SQLStringDropTable NVARCHAR(MAX);
SET #SQLStringDropTable= 'DROP TABLE' + ' ' +
'[#ItemAreaCode].[ChangedRMAllocation]'
PRINT #ItemAreaCode
EXEC sp_executesql #SQLStringDropTable , N'#ItemAreaCode NVARCHAR(MAX)', #ItemAreaCode;
But when I execute this, I get this error:
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table '#ItemAreaCode.ChangedRMAllocation', because it does not exist or you do not have permission.
And the printed query is..
DROP TABLE [#ItemAreaCode].[ChangedRMAllocation];
What I need is:
DROP TABLE [A062].[ChangedRMAllocation];
You are setting you parameter as a string within the dynamic SQL.
#ItemAreaCode should not be included.
This should work :
DECLARE #ItemAreaCode NVARCHAR(MAX) = 'A062',
#SQLStringDropTable NVARCHAR(MAX);
SET #SQLStringDropTable= 'DROP TABLE' + ' ['
+ #ItemAreaCode + '].[ChangedRMAllocation]'
PRINT #ItemAreaCode
EXEC (#SQLStringDropTable);
Hope this helps
You probably meant to expand the variable:
DECLARE #ItemAreaCode sysname = 'A062',
#SQLStringDropTable NVARCHAR(MAX);
SET #SQLStringDropTable =
'DROP TABLE ' + quotename(#ItemAreaCode) + '.[ChangedRMAllocation]';
EXEC (#SQLStringDropTable);
Try this
DECLARE #ItemAreaCode NVARCHAR(MAX) = 'A062'
,#SQLStringDropTable NVARCHAR(MAX);
SET #SQLStringDropTable = 'DROP TABLE [' + #ItemAreaCode + '].[ChangedRMAllocation]'
EXEC (#SQLStringDropTable)

sql server stored procedure single quotes

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