I am pretty new to SQL Server and hope someone here can help me with this (I'm using QL Server 2008).
The following is a small procedure that works as intended.
Now I would like to use the same procedure to update multiple tables as all these tables have exactly the same column names and column formatting, the only difference is the 2nd part of the table name for which I added XXX below.
Can someone tell me how this could be made dynamic and also provide me some explanations on this ?
I cannot provide much more here as I wasn't sure about how to approach this - other than probably declaring #sql nvarchar(max) and wrapping the whole query in SET #sql = N'...' before executing it.
My stored procedure:
CREATE PROCEDURE [dbo].[Cal_UpdateTeam]
#team nvarchar(100),
#teamID int,
#notes nvarchar(1000),
#log nvarchar(100),
#admin varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
IF NOT EXISTS
(
SELECT *
FROM Cal_XXX
WHERE teamID = #teamID
)
INSERT INTO Cal_XXX
(
team,
teamID,
notes,
log,
admin
)
SELECT #team,
#teamID,
#notes,
#log,
#admin
ELSE
UPDATE Cal_XXX
SET team = #team,
teamID = #teamID,
notes = #notes,
log = #log,
admin = #admin
WHERE teamID = #teamID
END
END
Many thanks for any tips and advise on this, Mike.
you should wrap your sql query in an nvarchar and then execute that query as in the below example :
declare #sql nvarchar(max)
declare #TableName nvarchar(max)
set #TableName = 'mytable'
set #sql = 'Select * from ' + #TableName
Exec sp_executesql #sql
in SP you can use Temporary Tables fro example:
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/*************************************
** Temporary table **
*************************************/
CREATE TABLE #SOURCE (
ID INT
, ID_PARENT INT
, NAME VARCHAR(200)
, SORT INT
..
..
)
IF #REQUEST_ID = 'YES' BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_A
END
ELSE BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_B
END
SELECT * FROM #SOURCE
.....
END
GO
in SP you can encapsulate other SPs with different table names like parameter:
CREATE PROCEDURE SELECT_FROM_TABLE_A
AS
BEGIN
SELECT * FROM SOURCE_A
END
GO
CREATE PROCEDURE SELECT_FROM_TABLE_B
AS
BEGIN
SELECT * FROM SOURCE_B
END
GO
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/**********************************************
** Subrequest select **
**********************************************/
IF #REQUEST_ID = 'YES' BEGIN
-- Request SP fro Source A
EXEC SELECT_FROM_TABLE_A
END
ELSE
BEGIN
-- Request SP fro Source B
EXEC SELECT_FROM_TABLE_B
END
END
GO
Related
Does anyone know why this query doesn't work? How to add the table variable itemId as parameter to the exec statement? Thanks
DECLARE #test TABLE
(
itemId UNIQUEIDENTIFIER,
finalAmount DECIMAL
);
INSERT INTO #test EXEC [GetItems]
DECLARE #sql NVARCHAR(max)
DECLARE #param NVARCHAR(max)
SET #param = N'select itemId from #test'
SELECT #sql = 'EXEC [InsertTestItem]'+' ' + #param;
SELECT #sql
EXEC(#sql)
See a full working example in SQL Server, you should be able to run each block one after the other to see that its selected everything from your table type that you pass in to the stored proc
-- Create the Table type that we will use in the stored proc------------------------
IF NOT EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyIdTableType')
BEGIN
PRINT 'Creating type [dbo].[MyIdTableType]'
CREATE TYPE [dbo].MyIdTableType AS TABLE (
Id BIGINT
)
END
GO
-- Create a stored proc that uses it ------------------------
CREATE PROCEDURE [dbo].[UsMyTabelType]
#IdsTable AS [dbo].MyIdTableType Readonly
AS
BEGIN
-- Now you have the data you can use it like any normal table and join on it
SELECT * FROM #IdsTable
END
GO
-- Lets test it out ------------------------
DECLARE #myIds AS MyIdTableType
INSERT INTO #myIds (Id)
VALUES
(1),
(2),
(3)
EXEC dbo.UsMyTabelType #IdsTable = #myIds
I am using SQL Server 2008 R2. I am having some problems finding an effective coding pattern for SQL which supports code re-usability as well as flexibility. By re-usability, what I mean is keeping SQL queries in Stored Procedures and User Defined Functions.
Now, if I choose Stored Procedures, I will be sacrificing its usability in a query directly. If I choose User Defined Functions, I won't be able to use DML statements.
For example, suppose I created a Stored Procedures which inserts one contact record. Now, if I am having a table which can act as a source of multiple contact records, all I am left with are either WHILE loops or CURSORs, which is clearly not a recommended option, due to its performance drawbacks. And due to the fact that DML statements are not allowed in User Defined Functions, I simply cannot use them for this purpose.
Although, If I am not concerned with code re-usability, then instead of using Stored Procedures I can surely use same set of queries again and again to avoid while loops.
What pattern should I follow?
Here is a similar Stored Procedures:-
ALTER Proc [dbo].[InsertTranslationForCategory]
(
#str nvarchar(max),
#EventId int,
#CategoryName NVarchar(500),
#LanguageId int,
#DBCmdResponseCode Int Output,
#KeyIds nvarchar(max) Output
)as
BEGIN
DECLARE #XmlData XML
DECLARE #SystemCategoryId Int
DECLARE #CategoryId Int
Declare #Counter int=1
Declare #tempCount Int
Declare #IsExists int
Declare #TranslationToUpdate NVarchar(500)
Declare #EventName Varchar(200)
declare #Locale nvarchar(10)
declare #Code nvarchar(50)
declare #KeyName nvarchar(200)
declare #KeyValue nvarchar(500)
select #Locale=locale from languages where languageid = #LanguageId
SET #DBCmdResponseCode = 0
SET #KeyIds = ''
select #EventName = eventName from eventLanguages
where eventID = #EventId
--BEGIN TRY
Select #SystemCategoryId=CategoryId from SystemCategories where Name=rtrim(ltrim(#CategoryName))
Select #CategoryId=CategoryId from Categories where Name=rtrim(ltrim(#CategoryName)) and EventId=#EventId
if (#str='deactivate')
Begin
Delete from Codetranslation where CategoryId=#CategoryId
Update Categories set [Status]=0, Isfilter=0 where CategoryId=#CategoryId and Eventid=#EventId
Set #DBCmdResponseCode=2
return
End
set #XmlData=cast(#str as xml)
DECLARE #temp TABLE
(
Id int IDENTITY(1,1),
Code varchar(100),
Translation varchar(500),
CategoryId int
)
Insert into #temp (Code,Translation,CategoryId)
SELECT
tab.col.value('#Code', 'varchar(200)'),
tab.col.value('#Translation', 'varchar(500)'),#SystemCategoryId
FROM #XmlData.nodes('/Data') AS tab (col)
select #tempCount=Count(*) from #temp
if(IsNull(#CategoryId,0)>0)
Begin
While (#Counter <= #tempCount)
Begin
Select #IsExists= count(sc.categoryid) from #temp t Inner Join SystemCodetranslation sc
On sc.categoryid=t.CategoryId
where ltrim(rtrim(sc.code))=ltrim(rtrim(t.code)) and ltrim(rtrim(sc.ShortTranslation))=ltrim(rtrim(t.Translation))
and t.Id= #Counter
print #IsExists
Select #Code = Code , #KeyValue = Translation from #temp where id=#counter
set #KeyName = ltrim(rtrim(#EventName)) + '_' + ltrim(rtrim(#CategoryName)) + '_' + ltrim(rtrim(#Code)) + '_LT'
exec dbo.AddUpdateKeyValue #EventId,#Locale, #KeyName,#KeyValue,NULL,12
select #KeyIds = #KeyIds + convert(varchar(50),keyvalueId) + ',' from dbo.KeyValues
where eventid = #EventId and keyname = #KeyName and locale = #Locale
set #KeyName = ''
set #KeyValue = ''
Set #Counter= #Counter + 1
Set #IsExists=0
End
End
--- Inser data in Codetranslation table
if(isnull(#CategoryId,0)>0)
Begin
print #CategoryId
Delete from codetranslation where categoryid=#CategoryId
Insert into codetranslation (CategoryId,Code,LanguageId,ShortTranslation,LongTranslation,SortOrder)
SELECT
#CategoryId,
tab.col.value('#Code', 'varchar(200)'), #LanguageId,
tab.col.value('#Translation', 'varchar(500)'),
tab.col.value('#Translation', 'varchar(500)'),0
FROM #XmlData.nodes('/Data') AS tab (col)
Update Categories set [Status]=1 where CategoryId=#CategoryId and Eventid=#EventId
End
Set #DBCmdResponseCode=1
set #KeyIds = left(#KeyIds,len(#KeyIds)-1)
END
You can use table variable parameter for your user defined functions.
following code is an example of using table variable parameter in stored procedure.
CREATE TYPE IdList AS TABLE (Id INT)
CREATE PROCEDURE test
#Ids dbo.IdList READONLY
AS
Select *
From YourTable
Where YourTable.Id in (Select Id From #Ids)
End
GO
In order to execute your stored procedure use following format:
Declare #Ids dbo.IdList
Insert into #Ids(Id) values(1),(2),(3)
Execute dbo.test #Ids
Edit
In order to return Inserted Id, I don't use from Table Variable Parameter. I use following query sample for this purpose.
--CREATE TYPE NameList AS TABLE (Name NVarChar(100))
CREATE PROCEDURE test
#Names dbo.NameList READONLY
AS
Declare #T Table(Id Int)
Insert Into YourTable (Name)
OUTPUT Inserted.Id Into #T
Select Name
From #Names
Select * From #T
End
GO
I'm trying to write a script that can be used to restore permissions to stored procedures after our merge replication snapshot agent completes applying snapshot to subscribers. This SQL needs to be somewhat dynamic.
Currently, I'm selecting a list of all our stored procedures and inserting them into a temporary table along with string statements for "Granting" permissions. I'm attempting to loop through all the rows on that table, executing the statements one by one using EXEC() command. I keep getting the error
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
but my SQL statements look like they should be fine. Maybe I'm not understanding how WHILE works in SQL Server.
Here is my code:
BEGIN
CREATE TABLE sqltemp (id int IDENTITY(1, 1) , Stmt1 varchar(max), Stmt2 varchar(max), Stmt3 varchar(max))
INSERT INTO sqltemp
SELECT
'GRANT EXECUTE ON OBJECT::' as Stmt1, name as Stmt2, 'TO edoc_only_execute' as Stmt3
FROM sys.sysobjects
WHERE
type = 'P' AND name NOT LIKE 'MSMerge%'
DECLARE #counter int = 1
WHILE (#counter < (SELECT COUNT(*) FROM sqltemp))
BEGIN
DECLARE #sqlrun varchar(max)
SET #sqlrun = (SELECT Stmt1, Stmt2, Stmt3 FROM sqltemp WHERE id = #counter)
EXEC(#sqlrun)
SET #counter = #counter + 1
END
END
GO
DROP TABLE sqltemp
Two questions:
How can I accomplish executing the above script for each item in my temporary table?
Is there a better way of writing a script to restore permissions for each stored procedure in my database after the snapshot is applied (Note: I must be able use SQL system tables to pull stored procedure names)?
You can't say
SET #sqlrun = (SELECT Stmt1, Stmt2, Stmt3 FROM sqltemp WHERE id = #counter)
You will have to concatenate them
SELECT #sqlrun = Stmt1 +' '+ Stmt2 +' '+ Stmt3 FROM sqltemp WHERE id = #counter
A better solution might be?
GRANT EXEC TO edoc_only_execute
Corrected query for you first question
BEGIN
CREATE TABLE sqltemp (id int IDENTITY(1, 1) , Stmt1 varchar(max), Stmt2 varchar(max), Stmt3 varchar(max))
INSERT INTO sqltemp SELECT 'GRANT EXECUTE ON OBJECT::' as Stmt1, name as Stmt2, 'TO edoc_only_execute' as Stmt3
FROM sys.sysobjects
WHERE type = 'P' AND name NOT LIKE 'MSMerge%'
DECLARE #counter int = 1
WHILE (#counter < (SELECT COUNT(*) FROM sqltemp))
BEGIN
DECLARE #sqlrun varchar(max)
SELECT #sqlrun = Stmt1 + Stmt2 +' '+ Stmt3 FROM sqltemp WHERE id = #counter
PRINT #sqlrun
EXEC(#sqlrun)
SET #counter = #counter + 1
END
END
#010001100110000101110010011010 and #podiluska beat me to it, but...
SELECT COUNT(*) FROM sqltemp
outside of the while:
SET #end = SELECT COUNT(*) FROM sqltemp
WHILE (#counter < #end)
...
No need to re-calculate the end condition for each loop iteration.
I have two very similar tables in our database, and I need to write a stored procedure for my Visual Studio 2010 Web Application to read the data from one of these tables given a table number.
Currently, we only have two tables to select from, but I can see this growing to more as this project grows.
This is sort of what I am trying to do, but this code is not correct:
PROCEDURE [dbo].[spGetData]
#tableID int
AS
BEGIN
SET NOCOUNT ON;
declare #col1 nvarchar(50), #table nvarchar(50)
set #col1=case when #tableID=1 then 'SMRequestID' else 'WHRequestID' end
set #table=case when #tableID=1 then 'SMRequest' else 'WHRequest' end
select #col1 as 'Request', WorkOrder, PartNumber, Qty, EmployeeID
from #table
END
Basically, the ColumnName and TableName depend on the #tableID parameter that will be passed in.
How would I go about doing that?
Note: My searches are not turning up anything related, but I am a C# developer and not a database developer. I imagine this has been asked before, it is just I am not using the right keywords.
Although I think Mark is quite correct given the small number of tables and simplicity of your queries, here is a dynamic sql example that passes both the table and column names:
CREATE PROCEDURE spGetData
(
#TableName nvarchar(128),
#ColumnName nvarchar(128)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(4000)
SET #SQL = 'SELECT ' + #ColumnName + ', as Request, WorkOrder, PartNumber, Qty, EmployeeID FROM ' + #TableName
EXEC sp_executesql #SQL
END
You can call it as follows:
exec spGetData 'SMRequest', 'SMRequestID'
exec spGetData 'WHRequest', 'WHRequestID'
One option would be to use a conditional based upon the ID and put the code for a specific table in each section for the table.
I prefer this method to get away from the dynamic sql and allow the database server to get a fighting chance to optimize the thing for speed reasons by precompiling.
NOTE: database servers are pretty bad at string manipulation (create dynamic sql) in general.
EDIT1: EXAMPLE
FOR INSTANCE: THIS SQL
declare #mytest varchar(5)
set #mytest = 'PROCS'
IF #mytest = 'PROCS'
BEGIN /* STORED PROCS */
SELECT DISTINCT
o.name AS ObjectName_StoredProcedure
FROM sysobjects as o
WHERE o.xtype = 'P'
END
ELSE
IF #mytest = 'DEFAULT'
BEGIN
SELECT DISTINCT
o.name AS ObjectName_StoredProcedure
FROM sysobjects as o
WHERE o.xtype = 'D'
END
gives you the store procedure names or the default constraints depending on what you pass to the parameter.
EDIT2: Based on OP code:
CREATE PROCEDURE [dbo].[spGetData]
(#tableID int )
AS
BEGIN
SET NOCOUNT ON;
IF #tableID = 1
BEGIN
SELECT SMSRequestId AS 'Request',
WorkOrder, PartNumber, Qty, EmployeeID
FROM SMRequest
END
IF #tableID = 2
BEGIN
SELECT WHRequestID AS 'Request',
WorkOrder, PartNumber, Qty, EmployeeID
FROM WHRequest
END
END
Do it with dynamic SQL:
PROCEDURE [dbo].[spGetData]
#tableID int
AS
BEGIN
SET NOCOUNT ON;
declare #col1 nvarchar(50), #table nvarchar(50), #cmd nvarchar(400)
set #col1=case when #tableID=1 then 'SMRequestID' else 'WHRequestID' end
set #table=case when #tableID=1 then 'SMRequest' else 'WHRequest' end
#cmd = "select " + #col1 + " as 'Request', WorkOrder, PartNumber, Qty, EmployeeID from " + #table
EXEC(#cmd)
END
Does anyone know how to write a script in stored proc to run the table based on the variable (or will it possible to do so?)?
for example:
I have 3 tables name called customer, supplier, and support
when user input 1, then run table customer, 2 table supplier and 3 table support
declare #input int;
if #input =1
begin
declare #table varchar(50); set #table = 'customer'
end
if #input =2
begin
declare #table varchar(50); set #table = 'supplier '
end
if #input =3
begin
declare #table varchar(50); set #table = 'support'
end
select *
INTO ##test
from #table
IF it really is that simple, why not just repeat the Select?
if #input =1
begin
Select * INTO ##test From customer
end
if #input =2
begin
Select * INTO ##test From supplier
end
if #input =3
begin
Select * INTO ##test From support
end
yes you can do it by using dynamic sql "EXEC" or by "Sp_Executesql" command.
Example :
USE Northwind
GO
CREATE TABLE #MyTemp
( RowID int IDENTITY,
LastName varchar(20)
)
DECLARE #SQL nvarchar(250)
SET #SQL = 'INSERT INTO #MyTemp SELECT LastName FROM Employees;'
EXECUTE sp_executesql #SQL
Why do you want to do this? It seems like a bad idea at first glance.
Can you post what your stored procedure is doing and any relevant tables? I suspect that you may be able to either:
Modify your schema in such a way
that you would no longer to do
this
Create different stored procedures
to do what you want on each table instead of forcing it into one proc.
There are several issues that come up when you use dynamic SQL that you should be aware of. Here is a fairly comprehensive article on the pros and cons.