how to pass tablename as parameter in sql server - sql

hello frnds i need to pass a table name as parameter to stored procedure
CREATE PROCEDURE six #tablename nvarchar
AS
SELECT * FROM + #tablename
Go
exec six Entry_sixsigma_mag
it gives error like
Msg 102, Level 15, State 1, Procedure six, Line 3
Incorrect syntax near '+'.
Msg 208, Level 16, State 1, Procedure six, Line 3
Invalid object name '#sixsigma'.

Try something like
CREATE PROCEDURE six #tablename nvarchar(100)
AS
EXEC('SELECT * FROM ' + #tablename)
Go
exec six Entry_sixsigma_mag
Have a look at EXECUTE (Transact-SQL)
But you should also have a look at
SQL Injection
Dynamic SQL & SQL injection
before using this blindly.

Related

Execute the output of an SP

I have a stored procedure 'GetInsertTrigger' which returns below Output.
I need to concat these lines and execute it again.
Also, I cannot insert this output into temp table.
create table #otable (line nvarchar(max))
insert into #otable (line)
exec GetInsertTrigger #TableName = 'cci_parms_mst'
Error msg is
Msg 8164, Level 16, State 1, Procedure GetInsertTrigger , Line 1266 [Batch Start Line 64]
An INSERT EXEC statement cannot be nested.
I cannot modify GetInsertTrigger as it is standard in our system.

How can I insert text, from a subquery, in a function request

I'm using a function on the Master database (xp_fileexist) to check if a folder is empty or not. If it's empty I want a 0, otherwise a 1.
If I hardcode the folder name ('C:\Import\2016-01-01\Transaction') it works fine. What doesn't work for me, is having the date as a variable, as the date changes from time to time. For the variable, I use this:
'C:\Import\The Netherlands\'+CAST((select workingdate from system..tmpworkingdate) AS VARCHAR(10))+'\Transaction(BP)'
This is the code I've tried:
CREATE TABLE #temp (FileExists int, IsDirectory int, ParentDirExists int)
INSERT INTO #temp
EXEC master..xp_fileexist ('C:\Import\'+CAST((select workingdate from system..tmpworkingdate) AS VARCHAR(10))+'\Transaction(BP)')
IF EXISTS(SELECT IsDirectory FROM #temp WHERE IsDirectory=1)
PRINT 1
ELSE
PRINT 0
DROP TABLE #temp
Error: Msg 102, Level 15, State 1, Line 5 Incorrect syntax near
'C:\Import\The Netherlands\'. Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'AS'.
Does anyone have a clue?
EXEC doesn't allow string manipulations (or any expression evaluation). Define the value beforehand:
DECLARE #filename VARCHAR(MAX);
SET #filename = 'C:\Import\'+CAST((select workingdate from system..tmpworkingdate) AS VARCHAR(10))+'\Transaction(BP)';
EXEC master..xp_fileexist (#filename);
That said, you should use CONVERT() or FORMAT() to be sure you get the format you really want. You wouldn't want system changes to totally break this code.
EDIT:
Argg! I didn't realize that EXEC master..xp_fileexist doesn't even allow string variables on the execution line. So, you have to do the whole thing as dynamic SQL:
DECLARE #sql NVARCHAR(MAX) = 'EXEC master..xp_fileexist ''' + #filename + '''';
EXEC(#sql);
(There are examples on the web that do use variables, so maybe this depends on the SQL Server version.)

Syntax error in sql exec count

declare #message int,#DBName varchar(50)
set #DBName ='AutoChip'
exec('select '+#message+'= count(*) from '+#DBname+'.[dbo].[Report List]')
print #message
Getting an error trying to print the count
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
I will pass DBname dynamically, I am using a cursor
The variable name needs to be part of dynamic SQL you are creating, but it's shouldn't be concated with it.
For example, if your variable is of type varchar and has value as 'ERROR', resultant query will be
select ERROR= count(*) from YOURDBNAME.[dbo].[Report List]
so the correct one is below.
exec('select #message= count(*) from '+#DBname+'.[dbo].[Report List]')
You need to include variable declaration and initialization in dynamic sql. You cannot set a value of external variable inside a dynamic sql as the context of execution will be different.

Stored procedure for a login with user and password as parameter

create procedure createacc(
#loginnaam nvarchar(30),
#wachtwoord nvarchar(30))
AS
CREATE LOGIN #loginnaam
WITH PASSWORD = #wachtwoord
CREATE USER #loginnaam FOR LOGIN #loginnaam
ALTER ROLE db_datareader ADD #loginnaam
Go
This gives me syntax errors while it works fine outside of the Stored Procedure.
Msg 102, Level 15, State 1, Procedure createacc, Line 5
Incorrect syntax near '#loginnaam'.
Msg 319, Level 15, State 1, Procedure createacc, Line 6
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Msg 156, Level 15, State 1, Procedure createacc, Line 8
Incorrect syntax near the keyword 'ADD'.
I would suggest using dynamic sql for this. Declare a nvarchar variable, put your statement inside it and execute that statement.
For example in your case:
DECLARE #statement NVARCHAR(MAX)
SET #statement = 'CREATE LOGIN ' + #loginnaam + ' WITH PASSWORD = '''+ #wachtwoord + ''' ;'
exec (#statement)
Above answer may be velnarable to SQL injection, it is concating SQL statement and then executing it.
Is there any way to pass password string as a parameter like example below
declare #query nvarchar(500)
declare #params nvarchar(500)
declare #passwordVal nvarchar(100)
set #passwordVal=N'Test#123'
set #query = 'Alter LOGIN [SqlUser] WITH password=#pass'
set #params = N'#pass NVARCHAR (100)';
EXECUTE sp_executesql #query,#params, #pass=#passwordVal
This query generates error
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '#pass'.
Better alternative answer to parameter is here
I am trying to create a stored procedure to create a login and a database user?

Error in reading CSV file

I am using the below code in SP, SQL Server 2005
declare #path varchar(500)
set #path = 'E:\Support\test.csv';
print #path
Create table #mytable(
name varchar(max), class varchar(max), roll varchar(max)
)
BULK INSERT #mytable FROM #path
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
);
Go
select * from #mytable
drop table #mytable
But it is throwing the following error :
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '#path'.
Msg 319, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'with'.
If this statement is a common table expression or an xmlnamespaces clause,
the previous statement must be terminated with a semicolon.
Msg 208, Level 16, State 0, Line 1
Invalid object name '#mytable'.
Could anybody help me.
You can't do the following
BULK INSERT #mytable FROM #path
if you are expecting this to translate to
BULK INSERT #mytable FROM 'E:\Support\test.csv'
It's not the file name that's in the varchar, SQL sees it #Path as the data and not a string containing the path.
If you need to use a variable for the path, you will need to use some dynamic SQL which roughly translates to (excuse syntax errors)
DECLARE #SQL varchar(max)
SET #SQL = 'BULK INSERT #mytable FROM '+ #path + '
--Add the rest of your code here
EXEC (#SQL)
If your variable is never going to change though I'd just go ahead and stick the string into the statement itself.
Hope that helps.