I have a problem here, I'm searching in stackoverflow but still not find the best way
i have a stored procedure (SP) like this
DECLARE #table NVARCHAR(max), #SQLQuery NVARCHAR(max)
SET #table = #meta+'_prize4winner'
SET #SQLQuery = 'if exists (Select * from [dbo].' + #table + ' where idCampaignLog =''' + convert(nvarchar, #ID) +''') exec InsertC2CWinner''' + convert(nvarchar, #meta) +''','''+ convert(nvarchar, #ID)+''',null else select ''you lose ''as winStatus'
execute SP_EXECUTESQL #SQLQuery
need help how and where to set the output if I want the output if exist 'YOU WIN' else 'You Lose' thx
The general syntax is like this
DECLARE #retval int
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #tablename nvarchar(50)
SELECT #tablename = N'products'
SELECT #sSQL = N'SELECT #retvalOUT = MAX(ID) FROM ' + #tablename;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;
Related
I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END
I would like to add the following stored procedure to all existing databases which contain the table schichten. All my approaches have failed so I'm looking for help here.
This is my approach:
IF object_id('tempdb.dbo.#database') is not null
drop TABLE #database
GO
CREATE TABLE #database(id INT identity primary key, name sysname)
GO
SET NOCOUNT ON
INSERT INTO #database(name)
SELECT name
FROM sys.databases
WHERE source_database_id is null
ORDER BY name
SELECT * FROM #database
DECLARE #id INT, #cnt INT, #sql NVARCHAR(MAX), #currentDb SYSNAME;
SELECT #id = 1, #cnt = max(id) FROM #database
WHILE #id <= #cnt
BEGIN
BEGIN TRY
SELECT #currentDb = name
FROM #database
WHERE id = #id
IF OBJECT_ID(#currentDb+'.dbo.schichten') IS NOT NULL
CREATE PROCEDURE #currentDb.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = 'konz'
BEGIN
SET #ASSelector = 'Taxi'
SET #IFPers=''
END
ELSE
BEGIN
SET #ASSelector = 'Personal'
SET #IFPers = '[name] AS Name,'
END
SET #sql1 = N';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL(['+ #Selector +'],0) AS '+ #ASSelector +','+ #IFPers +'
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN ('+ #ColumnName + N' )) AS UMSAETZE )
SELECT *, '+ #Gesamtergebnis +' AS Gesamtergebnis FROM temp ORDER BY '+ #ASSelector +''
EXEC sp_executesql #sql
END
END TRY
BEGIN CATCH
END CATCH
SET #id = #id + 1;
END
GO
I am hoping that there is someone who can help me.
You have to execute the create procedure separately, so if you wrap it up into a variable and use exec sp_executesql it should work.
IF object_id('tempdb.dbo.#database') is not null
drop TABLE #database
GO
CREATE TABLE #database(id INT identity primary key, name sysname)
GO
SET NOCOUNT ON
INSERT INTO #database(name)
SELECT name
FROM sys.databases
WHERE source_database_id is null
ORDER BY name
SELECT * FROM #database
DECLARE #id INT, #cnt INT, #sql NVARCHAR(MAX), #currentDb SYSNAME;
SELECT #id = 1, #cnt = max(id) FROM #database
WHILE #id <= #cnt
BEGIN
BEGIN TRY
SELECT #currentDb = name
FROM #database
WHERE id = #id
IF OBJECT_ID(#currentDb+'.dbo.schichten') IS NOT NULL
begin
set #sql = 'CREATE PROCEDURE '+#currentDb+'.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = ''konz''
BEGIN
SET #ASSelector = ''Taxi''
SET #IFPers=''''
END
ELSE
BEGIN
SET #ASSelector = ''Personal''
SET #IFPers = ''[name] AS Name,''
END
SET #sql1 = N'';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL([''+ #Selector +''],0) AS ''+ #ASSelector +'',''+ #IFPers +''
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN (''+ #ColumnName + N'' )) AS UMSAETZE )
SELECT *, ''+ #Gesamtergebnis +'' AS Gesamtergebnis FROM temp ORDER BY ''+ #ASSelector +''''
EXEC sp_executesql #sql1
END'
EXEC sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
SET #id = #id + 1;
END
GO
Assuming this is a one time need as opposed to a nightly maintenance task, you can use a built-in stored procedure, sys.sp_MSforeachdb, to execute a statement in each database. It is safe to use and has been discussed extensively on the web. However, it is an undocumented feature and can be removed without notice by Microsoft so you don't want to depend on it for recurring tasks.
Create and validate your statement in one database, then use this stored procedure to execute it in all of the databases. ? is the placeholder for the database name.
EXEC sys.sp_MSforeachdb #command1 =
'IF OBJECT_ID(''?.dbo.schichten'') IS NOT NULL
AND OBJECT_id(''?.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]'') IS NOT NULL
BEGIN
CREATE PROCEDURE ?.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = ''konz''
BEGIN
SET #ASSelector = ''Taxi''
SET #IFPers=''''
END
ELSE
BEGIN
SET #ASSelector = ''Personal''
SET #IFPers = ''[name] AS Name,''
END
SET #sql1 = N'';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL([''+ #Selector +''],0) AS ''+ #ASSelector +'',''+ #IFPers +''
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN (''+ #ColumnName + N'' )) AS UMSAETZE )
SELECT *, ''+ #Gesamtergebnis +'' AS Gesamtergebnis FROM temp ORDER BY ''+ #ASSelector +''''
EXEC sp_executesql #sql1
END
'
I would like to ask how am I going to return the count(*) because every time I call the stored procedure, it just prints the result.
Here is the code :
ALTER PROCEDURE sp_returnCount
#tblname sysname
, #colname sysname
, #key varchar(10)
AS
DECLARE #sql nvarchar(4000)
DECLARE #num INT
DECLARE #params NVARCHAR (4000)
SELECT #sql = 'SELECT COUNT(*) ' +
' FROM dbo.' + quotename(#tblname) +
' WHERE ' + quotename(#colname) + ' LIKE #key'
EXEC sp_executesql #sql, N'#key varchar(10)', #key
--just prints 5 or any numbers...
I'd like to return the count(*) to use it in another query. Thanks in advance.
ALTER PROCEDURE sp_returnCount
#tblname sysname
, #colname sysname
, #key varchar(10)
AS
DECLARE #sql nvarchar(4000)
DECLARE #num INT
DECLARE #params NVARCHAR (4000)
DECLARE #count int
SELECT #sql = 'SELECT #count = COUNT(*) ' +
' FROM dbo.' + quotename(#tblname) +
' WHERE ' + quotename(#colname) + ' LIKE #key'
EXEC sp_executesql #sql, N'#key varchar(10), #count int OUTPUT', #key, #count OUTPUT
What is the best way to achieve this
INSERT INTO #TableName (#ColumnNames)
EXEC sp_executesql #SQLResult;
Where #TableName, #ColumnNames, #SQLResult are varchar variables
I am trying to avoid do a separate insert for each table.
The best way is to write (or generate) all reqiured procedures for all table. 23 tables times 4 procedures (insert, update, delete and select) that can be generated automatically is nothing in dev time and pain compared to the so called "generic solution".
It's a path to poor perfomance, unreadable code, sql injection hazard and countless debuging hours.
First of all I appreciate all your comments. And I agree that SQL dynamic is a pain to debug (Thanks God, management studio has this possibility). And, of course there are hundreds of different solutions
I solved it in this way finally, more or less I try to explain why this solution of SQL dynamic. The client uses xlsx spreadsheets to enter certain data, so I read the spreadsheets and I insert the (data depends on the spreadsheet to insert into the proper table). Later the data in the tables are exported to XML to send a third party sofware.
SET #SEL = N'';
DECLARE sel_cursor CURSOR
FOR (SELECT sc.name as field
FROM sys.objects so INNER JOIN sys.columns sc ON so.[object_id]=sc.[object_id]
WHERE so.name= #TableName and sc.name not in ('InitDate', 'EndDate', 'Version', 'Status'));
SET #SEL = ''; set #i = 0;
OPEN sel_cursor
FETCH NEXT FROM sel_cursor INTO #field
WHILE ##FETCH_STATUS = 0
BEGIN
set #sel = #sel + ', '+ #field
set #i = 1;
FETCH NEXT FROM sel_cursor INTO #field
END
CLOSE sel_cursor;
DEALLOCATE sel_cursor;
SET #SQL = N''
SET #SQL = #SQL + N'SELECT * INTO XLImport FROM OPENROWSET'
SET #SQL = #SQL + N'('
SET #SQL = #SQL + N'''Microsoft.ACE.OLEDB.12.0'''+','
SET #SQL = #SQL + N'''Excel 12.0 Xml; HDR=YES;'
SET #SQL = #SQL + N'Database='+#file +''''+ ','
SET #SQL = #SQL + N'''select * from ['+ #SheetName + '$]'''+');'
EXEC sp_executesql #SQL
SET #SQL = N'';
SET #SQL = #SQL + N'
SELECT '+''''+CAST(#initDate AS VARCHAR(10))+'''' +', '+ ''''+CAST(#endDate AS VARCHAR(10))+''''
+ ', '+ CAST(#version AS VARCHAR(2)) +', ' +''''+#status+''''
+ #SEL
+' FROM DBO.XLImport '
DECLARE cols_cursor CURSOR
FOR (Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS where table_name = #tableName);
SET #SEL = ''; set #i = 0;
OPEN cols_cursor
FETCH NEXT FROM cols_cursor INTO #field
WHILE ##FETCH_STATUS = 0
BEGIN
set #sel = #sel + #field + ', '
set #i = 1;
FETCH NEXT FROM cols_cursor INTO #field
END
CLOSE cols_cursor;
DEALLOCATE cols_cursor;
SET #SEL = LEFT(#SEL, LEN(#SEL) - 1) -- remove last ,
SET #SQL = N''
SET #SQL = #SQL + N'SELECT * INTO XLImport FROM OPENROWSET'
SET #SQL = #SQL + N'('
SET #SQL = #SQL + N'''Microsoft.ACE.OLEDB.12.0'''+','
SET #SQL = #SQL + N'''Excel 12.0 Xml; HDR=YES;'
SET #SQL = #SQL + N'Database='+#file +''''+ ','
SET #SQL = #SQL + N'''select * from ['+ #SheetName + '$]'''+');'
EXEC sp_executesql #SQL
SET #SQLString =
N'INSERT INTO '+ #TableName + '('+ #SEL +') ' + #SQL;
EXEC sp_executesql #SQLString
Use EXECUTE sp_executesql #sql, here is example:
create proc sp_DynamicExcuteStore
#TableName varchar(50),
#ColumnNames varchar(50),
#SQLResult varchar(max)
as
declare #sql nvarchar(max) = '
INSERT INTO '+#TableName+' ('+#ColumnNames+')
EXEC sp_executesql '+#SQLResult
EXECUTE sp_executesql #sql
go
create proc sp_test
as
select 'test' + convert(varchar,RAND())
go
CREATE TABLE [dbo].[Test](
[text1] [nvarchar](500) NULL
) ON [PRIMARY]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[sp_DynamicExcuteStore]
#TableName = N'Test',
#ColumnNames = N'text1',
#SQLResult = N'proc_test'
SELECT 'Return Value' = #return_value
GO
SELECT TOP 1000 [text1]
FROM [test].[dbo].[Test]
I am trying to insert ID values in stored procedure from .net and the int value for ID is inserting negative value in the stored procedure.
But when a negative value is passed its giving me an error incorrect syntax near '*'.
Please help me.
Here is my stored procedure
ALTER PROCEDURE [dbo].[HotlinePlusAdministration_ArticleMigrator]
#Id AS INT,
--#CategoryID AS INT,
--#Title AS Varchar(200),
--#ArticleDate AS datetime,
#DestLinkServer AS VARCHAR(50),
#UserID AS VARCHAR(8),
#ReturnMsg AS VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE #Query AS NVARCHAR(4000)
DECLARE #Log AS VARCHAR(8000)
DECLARE #ArticleID as int
DECLARE #NewArticleID as int
DECLARE #ArticleKeyExists as int
DECLARE #Title as varchar(200)
DECLARE #CategoryID as INT
DECLARE #ArticleDate as varchar(30)
DECLARE #ParmDefinition nvarchar(500);
SET XACT_ABORT ON -- Required for nested transaction
BEGIN TRAN
-- Check if ArticleID exists in Destination Server
SET #Query = N' SELECT #ArticleKeyExists = COUNT(*)
FROM ' + #DestLinkServer + '.HL2_61.dbo.Article' + ' where ArticleKey = ' + str(#Id)
SET #ParmDefinition = N' #ID int, #ArticleKeyExists int OUTPUT';
EXECUTE sp_executesql #Query , #ParmDefinition, #ID, #ArticleKeyExists OUTPUT;
--EXECUTE sp_executesql 1234,'BRHLSQL8','BRWSQLDC',#return = retnmsg
IF ##ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
SET #ReturnMsg = #Log + '<span style="color:red;">ERROR: <br></span>'
RETURN -1
END
--Delete existing Articles for select page
set #Query = 'DELETE FROM ' + #DestLinkServer +
'.HL2_61.dbo.Article ' +
'WHERE ArticleKey = ' + CONVERT(VARCHAR, #Id)
--'WHERE CategoryID = ' + CONVERT(VARCHAR, #CategoryID) + ' and Title = ''' + #Title + ''' and ArticleDate = ''' + #ArticleDate + ''''
Print #Query
EXEC(#Query)
When I am executing the code as below I am getting the error.
DECLARE #return_value int,
#ReturnMsg varchar(1000)
EXEC #return_value = [dbo].[Migrator]
#Id = -1591276581,
#DestLinkServer = N'SQLDC',
#UserID = N'10c1',
#ReturnMsg = #ReturnMsg OUTPUT
SELECT #ReturnMsg as N'#ReturnMsg'
SELECT 'Return Value' = #return_value
GO
Please someone help me..
Thanks
When you convert an int to a varchar, you have to specify the size:
Try this:
CONVERT(VARCHAR(50), #Id)
and avoid using str(#Id)