t-sql doesn't display anything in the column - sql-server

The following function doesn't return me anything in the colums even if going into debug mode it seams like the values are ok...
can someone help me out?
Obviously the select query on table [NewBiz.Labirinto].dbo.ElencoTipiEsercizio works and returns colums 2 colums:
id | dvr
1 | 1,2,3,4
2 | 1,3
4 | 1,2,4,5,6
USE [NuLab]
GO
/****** Object: UserDefinedFunction [dbo].[fun_CSVToTable] Script Date: 29/01/2015 17:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Function [dbo].[fun_CSVToTable]
(
#Delimeter varchar(10)
)
RETURNS #RET1 TABLE (id integer, dvr VARCHAR(50))
AS
BEGIN
DECLARE #RET TABLE(id integer, dvr VARCHAR(50))
DECLARE #RET2 TABLE(id integer, dvr VARCHAR(50))
DECLARE #ID integer
DECLARE #LIST varchar(50)
DECLARE #START BIGINT
DECLARE #LASTSTART BIGINT
DECLARE #VAR integer
set #ID = 0
set #VAR = 1
WHILE(#VAR IS NOT NULL)
BEGIN
IF (#ID > (select MAX(id) from [NewBiz.Labirinto].dbo.ElencoTipiEsercizio)) BREAK
set #LIST=(select dvr from [NewBiz.Labirinto].dbo.ElencoTipiEsercizio where [NewBiz.Labirinto].dbo.ElencoTipiEsercizio.id = #ID)
SET #LASTSTART=0
IF LTRIM(RTRIM(#LIST))='' RETURN
SET #START=CHARINDEX(#Delimeter,#LIST,0)
IF #START=0
INSERT INTO #RET(id, dvr) VALUES(#ID, SUBSTRING(#LIST,0,LEN(#LIST)+1))
WHILE(#START >0)
BEGIN
INSERT INTO #RET(id, dvr) VALUES(#ID, SUBSTRING(#LIST,#LASTSTART,#START-#LASTSTART))
SET #LASTSTART=#START+1
SET #START=CHARINDEX(#Delimeter,#LIST,#START+1)
IF(#START=0)
INSERT INTO #RET(id, dvr) VALUES(#ID, SUBSTRING(#LIST,#LASTSTART,LEN(#LIST)+1))
END
INSERT INTO #RET2 SELECT * FROM #RET
SET #ID = (select min(id) from [NewBiz.Labirinto].dbo.ElencoTipiEsercizio where id > #ID)
END
INSERT INTO #RET1 SELECT * FROM #RET2
RETURN
END

Related

How do I pass an existing table to a procedure? How do I use this... table-valued parameters thingys? look at my code below please

I have many tables that need ID scramblers, so:
CREATE PROCEDURE SP_generateUniqueID ( -- pass table here somehow -- )
AS
BEGIN
DECLARE #ID varchar(100) -- NEW ID.
DECLARE #isIDInUse tinyint -- BOOLEAN YES/NO.
SET #isIDInUse=1
WHILE(#isIDInUse=1) -- KEEP GENERATING TILL YOU FIND ONE:
BEGIN
SET #ID= dbo.generateID('aA1a1') -- GENERATES ID. doesn't matter how.
IF (#ID NOT IN (#passedTable)) -- DOES #ID EXIST ALREADY?
/*(SEARCHES THE PASSED TABLE! Which its size will be 1XN)*/
SET #isIDInUse=0 -- NO, YOU CAN USE.
END
RETURN #ID
END
I can't make the passing of the existing table go smoothly...
I want to be able to insert any table that uses IDs.
Any suggestion?
I would advise you REALLY look hard into better solutions for this issue. You will be hitting your table/index with every iteration of the new ID that you generate. What is wrong with an auto-incrementing integer value:
create table IDs (ID int identity(1,1))
(also, SQL Server has bit data types for boolean values. No need for your tinyint)
That aside, the only way I think you can do this your way is with dynamic SQL. Using the script below you should be able to see how you can pass in your schema.table to the stored procedure and within the procedure define your ID to be inserted in to the checking loop:
create table a(ID nvarchar(100)) insert into a values('1'),('2'),('3'),('4'),('5')
create table b(ID nvarchar(100)) insert into b values('6'),('7'),('8'),('9'),('10')
declare #Table nvarchar(100) = 'dbo.a'
declare #ID nvarchar(100) = '6'
declare #IDinUse bit = 0
declare #sql nvarchar(max) = 'if exists(select ID from ' + #Table + ' where ID = #ID) select #IDinUse = 1 else select #IDinUse = 0'
exec sp_executesql #sql, N'#ID nvarchar(100), #IDinUse bit output', #ID = #ID, #IDinUse = #IDinUse output
select #IDinUse as IDinUse
go
declare #Table nvarchar(100) = 'dbo.b'
declare #ID nvarchar(100) = '6'
declare #IDinUse bit = 0
declare #sql nvarchar(max) = 'if exists(select ID from ' + #Table + ' where ID = #ID) select #IDinUse = 1 else select #IDinUse = 0'
exec sp_executesql #sql, N'#ID nvarchar(100), #IDinUse bit output', #ID = #ID, #IDinUse = #IDinUse output
select #IDinUse as IDinUse

Cannot insert users in AspNetUsers table

I am trying to populate the AspNetUsers table using a stored procedure, but I get the following error:
Msg 515, Level 16, State 2, Procedure Insert_Users, Line 36 Cannot
insert the value NULL into column 'Id', table
'MyDatabase.dbo.AspNetUsers'; column does not allow nulls. INSERT
fails.
I read on some other posts that there should be the following attribute on the column Id: [DatabaseGenerated(DatabaseGeneratedOption.Identity)], but I cannot manage to find where is physically declared.
I don't want to insert all users manually because I'm out of time and I need to do it as quick as possible.
BEGIN
SET NOCOUNT ON;
DECLARE #id uniqueidentifier
DECLARE #email nvarchar(256)
DECLARE #emailconfirmed bit
SET #emailconfirmed = 0
DECLARE #twofactorenabled bit
SET #twofactorenabled = 0
DECLARE #lockoutenabled bit
SET #lockoutenabled = 1
DECLARE #accessFailed bit
SET #accessFailed = 1
DECLARE #username nvarchar(256)
DECLARE #fname nvarchar(50)
DECLARE #lname nvarchar(50)
DECLARE #athleteKey int
SET #athleteKey = 41809
DECLARE #atheletsCount int
SET #atheletsCount = 0;
SET #atheletsCount = (SELECT COUNT(*) FROM [BIBD].[dbo].[Athlete])
WHILE #athleteKey < #atheletsCount
SET #id = NEWID() --Line 36
print CAST(#id AS nvarchar(128))
SET #fname = (SELECT FirstName FROM [BIBD].[dbo].[Athlete] where AthleteKey=#athleteKey)
SET #lname = (SELECT LastName FROM [BIBD].[dbo].[Athlete] where AthleteKey=#athleteKey)
SET #username = CONCAT(LOWER(#fname),'.',LOWER(#lname))
SET #email = CONCAT(LOWER(#fname), '.', LOWER(#lname), '#gmail.com')
INSERT INTO [MyDatabase].[dbo].[AspNetUsers]
(Id
,Email
,EmailConfirmed
,[TwoFactorEnabled]
,LockoutEnabled
,AccessFailedCount
,UserName
,FirstName
,LastName)
VALUES
(CAST(#id AS nvarchar(128))
,#email
,#emailconfirmed
,#twofactorenabled
,#lockoutenabled
,#accessFailed
,#username
,#fname
,#lname)
IF #athleteKey % 5 = 0
INSERT INTO [MyDatabase].[dbo].[AspNetUserRoles]
(UserId,RoleId) VALUES (#id, 3)
ELSE
INSERT INTO [MyDatabase].[dbo].[AspNetUserRoles]
(UserId,RoleId) VALUES (#id, 4)
SET #athleteKey = #athleteKey+1
END
You need BEGIN-END in your WHILE loop.
Otherwise it just do not assign value to #id and does not process the loop

SQL SERVER : How to execute an SP specifed number of time without using loop

I have a scenario wherein i have to execute an SP for specified number of time(number of execution will be mentioned by user) without using loop.
My SP is setting an OUTPUT variable of varchar type. I am willing to insert the output of my SP into a temp table and use it for further processing.
I am unable to modify this SP into function as it contain an Update statement.
Kindly suggest if we can do so without loop.
Whit this solution you do not need an output; #res is your result directly set in a temp table.
CREATE PROCEDURE [dbo].[myStoredProc]
#Counter int,
#params nvarchar(64),
#CreateTable bit
AS
DECLARE #res varchar(64)
IF #CreateTable = 1
BEGIN
IF EXISTS (SELECT 1 FROM dbo.sysobjects WHERE id = object_id(N'[#tempTable]'))
DROP TABLE #tempTable
CREATE TABLE #tempTable ([Res] [nvarchar] (64))
END
SET #res = CONVERT(varchar(64), #Counter)
SET #Counter = #Counter - 1
IF #Counter > 0
exec myStoredProc #Counter, #params, 0
INSERT #tempTable VALUES (#res)
IF #CreateTable = 1
BEGIN
SELECT * FROM #tempTable
DROP TABLE #tempTable
END
GO
DECLARE #o varchar(64)
exec [myStoredProc] 5, '', 1

Conversion failed in cursor in stored procedure

Input like 111111 and 101,102,103,104
I want to check whether user has access on this requests or not...
I tried a cursor as shown, but I get this error:
Conversion failed when converting the varchar value '101,102,103,104' to data type int.
Code:
ALTER PROCEDURE [dbo].[ValidateRqstId]
#UserID VARCHAR(50),
#RsqtIDs VARCHAR(300)
AS
BEGIN
Declare #RqstId int
Declare #Result int
Declare #UserIDToCheck VARCHAR(50)
Declare #RqstUserVal cursor for
Select RequestId
from REQUEST_LIST
where RequestId in (#RsqtIDs)
BEGIN
OPEN RqstUserVal
FETCH NEXT from RqstUserVal into #RqstId
WHILE(##fetch_status <> -1)
BEGIN
SET #UserIDToCheck = (
select UserId from dbo.REQUEST_LIST where RequestId = #RqstId)
Print(#UserIDToCheck)
If(#UserIDToCheck != #UserID)
SET #Result = 99 ;
--Fetch the next row from the cursor
FETCH RqstUserVal into #RqstId
END
END
CLOSE RqstUserVal
Deallocate RqstUserVal
RETURN #Result
END
Thanks in advance
Depending on your SQL-Server Verion you can use a Table-Valued Function like in this short example
Select * from dbo.test1
Where ID in(
Select * from dbo.F_SplitAsIntTable('1,123,234,456'))
Function defined as
CREATE FUNCTION F_SplitAsIntTable
(
#txt varchar(max)
)
RETURNS
#tab TABLE
(
ID int
)
AS
BEGIN
declare #i int
declare #s varchar(20)
Set #i = CHARINDEX(',',#txt)
While #i>1
begin
set #s = LEFT(#txt,#i-1)
insert into #tab (id) values (#s)
Set #txt=RIGHT(#txt,Len(#txt)-#i)
Set #i = CHARINDEX(',',#txt)
end
insert into #tab (id) values (#txt)
RETURN
END
GO

Call Stored Procedure within Create Trigger in SQL Server

I have a stored procedure named insert2Newsletter with parameters
(#sex nvarchar(10),
#f_name nvarchar(50),
#l_name nvarchar(70),
#email nvarchar(75),
#ip_address nvarchar(50),
#hotelID int,
#maArt nchar(2))
I want call this stored procedure in an insert trigger. How do I retrieve the corresponding fields from inserted and how do i call insert2Newsletter within the trigger?
I tried without success:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER RA2Newsletter
ON [dbo].[Reiseagent]
AFTER INSERT
AS
DECLARE #rAgent_Name nvarchar(50),
DECLARE #rAgent_Email nvarchar(50),
DECLARE #rAgent_IP nvarchar(50),
DECLARE #hotelID int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select #rAgent_Name=rAgent_Name, #rAgent_Email=rAgent_Email, #rAgent_IP=rAgent_IP, #hotelID=hotelID From Inserted
EXEC insert2Newsletter '','',#rAgent_Name,#rAgent_Email,rAgent_IP,#hotelID,'RA'
END
GO
thx a lot for your feedback... greetings...
I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.
ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
AFTER INSERT
AS
-- This is your primary key. I assume INT, but initialize
-- to minimum value for the type you are using.
DECLARE #rAgent_ID INT = 0
-- Looping variable.
DECLARE #i INT = 0
-- Count of rows affected for looping over
DECLARE #count INT
-- These are your old variables.
DECLARE #rAgent_Name NVARCHAR(50)
DECLARE #rAgent_Email NVARCHAR(50)
DECLARE #rAgent_IP NVARCHAR(50)
DECLARE #hotelID INT
DECLARE #retval INT
BEGIN
SET NOCOUNT ON ;
-- Get count of affected rows
SELECT #Count = Count(rAgent_ID)
FROM inserted
-- Loop over rows affected
WHILE #i < #count
BEGIN
-- Get the next rAgent_ID
SELECT TOP 1
#rAgent_ID = rAgent_ID
FROM inserted
WHERE rAgent_ID > #rAgent_ID
ORDER BY rAgent_ID ASC
-- Populate values for the current row
SELECT #rAgent_Name = rAgent_Name,
#rAgent_Email = rAgent_Email,
#rAgent_IP = rAgent_IP,
#hotelID = hotelID
FROM Inserted
WHERE rAgent_ID = #rAgent_ID
-- Run your stored procedure
EXEC insert2Newsletter '', '', #rAgent_Name, #rAgent_Email,
#rAgent_IP, #hotelID, 'RA', #retval
-- Set up next iteration
SET #i = #i + 1
END
END
GO
I sure hope this helps you out. Cheers!
Finally ...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[RA2Newsletter]
ON [dbo].[Reiseagent]
AFTER INSERT
AS
declare
#rAgent_Name nvarchar(50),
#rAgent_Email nvarchar(50),
#rAgent_IP nvarchar(50),
#hotelID int,
#retval int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select
#rAgent_Name = rAgent_Name,
#rAgent_Email = rAgent_Email,
#rAgent_IP = rAgent_IP,
#hotelID = hotelID
From Inserted
EXEC insert2Newsletter
'',
'',
#rAgent_Name,
#rAgent_Email,
#rAgent_IP,
#hotelID,
'RA',
#retval
END
The following should do the trick - Only SqlServer
Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN
SET NOCOUNT ON;
Declare #id int
DECLARE #cDate as DateTime
set #cDate =(select Getdate())
select #id=deleted.Catagory_id from deleted
print #cDate
execute dbo.psp_Update_Category #id
END
Alter PROCEDURE dbo.psp_Update_Category
#id int
AS
BEGIN
DECLARE #cDate as DateTime
set #cDate =(select Getdate())
--Update Catagory_Master Set Modify_date=''+#cDate+'' Where Catagory_ID=#id --#UserID
Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END
You pass an undefined rAgent_IP parameter in EXEC instead of the local variable #rAgent_IP.
Still, this trigger will fail if you perform a multi-record INSERT statement.

Resources