Violation of Primary Key Constraint Query - sql

I was wondering if anyone could help me with my SQL code below. I am trying to insert all of the records from my BC_completions table into my Geodata table. If I exclude the ID column on the insert, I get a 'Msg 515... Cannot insert the value NULL into column 'ID'. But if I include it as below I get a 'Msg ...Violation of PRIMARY KEY constraint'.
What makes it more confusing is that if I manually typed in the value I get from #PK the database accepts it, so any help here would be great.
Thanks
DECLARE #PK AS INT
DECLARE #COUNT AS INT
DECLARE #RECORDCOUNT AS INT
SET #PK =
(SELECT TOP 1 ID FROM PRCORE.DBO.GEODATA
ORDER BY ID DESC)
SET #RECORDCOUNT =
(SELECT COUNT(*) FROM BC_COMPLETIONS)
SET #COUNT = 0
WHILE #COUNT < #RECORDCOUNT
BEGIN
SET #PK = #PK+1
SET #COUNT = #COUNT+1
INSERT INTO PRCORE.DBO.GEODATA
(ID,RecordType,ReferenceName,LocationDescription,Description,ORN,StartDate,ChgText)
SELECT #PK,189,REFVAL,ADDRESS,DSCRPN,ORN,RECPTD,AGTNAME
FROM BC_COMPLETIONS B
where #PK not in (select ID from prcore.dbo.geodata)
END

This is an issue with your loop and your WHERE constraint for the insert statement. You're selecting all of the records from BC_COMPLETIONS and assigning them to the same PK.
Instead, use the ROW_NUMBER() function to assign your PK which will allow you to do this all at once instead of one record at a time:
DECLARE #PK AS INT
DECLARE #RECORDCOUNT AS INT
SET #PK = (SELECT TOP 1 ID FROM PRCORE.DBO.GEODATA ORDER BY ID DESC) + 1
SET #RECORDCOUNT = (SELECT COUNT(*) FROM BC_COMPLETIONS)
INSERT INTO PRCORE.DBO.GEODATA (ID,RecordType,ReferenceName,LocationDescription,Description,ORN,StartDate,ChgText)
SELECT ROW_NUMBER() OVER(ORDER BY REFVAL) + #PK ,189,REFVAL,ADDRESS,DSCRPN,ORN,RECPTD,AGTNAME
FROM BC_COMPLETIONS B

Related

How to pass certain values from a table to a stored procedure

This is my problem. I have a table tbl_archivos with values like this:
Id desc namerc
---------------------------
1 arch1 RC201721091701
2 arch2 RC201724091701
I have to pass all the values of the column namerc in my table (above) to a stored procedure like parameter.
Like this :
sp_runproceess_billing 'RC201721091701'
and then the another value RC201724091701.
I am not allowed to use a cursor!
Please help me with this issue.
Thank you
try this solution
DECLARE #t AS TABLE(id INT PRIMARY KEY IDENTITY, namerc VARCHAR(50))
INSERT INTO #t
SELECT DISTINCT namerc FROM tbl_archivos
ORDER BY tbl_archivos
DECLARE #index INT = 1
DECLARE #max INT = (SELECT COUNT(*) FROM #t)
DECLARE #current_namerc VARCHAR(50)
WHILE #index <= #max
BEGIN
SELECT #current_namerc = namerc FROM #t WHERE id = #index
EXEC sp_runproceess_billing #current_namerc
SET #index = #index + 1
END

Can SQL use calculate values as alias names

I am trying to find out how to use a calculated value as part of an alias name .
For example:
Select employeeName as ''name of guy' but where 'name of guy' could be getdate() + 'name o guy'
Addin qualifiers just prevents the code inside from calculating.
Is this possible in any way? I'm going to use a partition to group results by year and I need the column aliases to be based on the year thy are in
I don't know if it's what you are looking for but it could be a good starting :
DECLARE #var table(rownum int, rowkey varchar(60), ALIAS varchar(80))
INSERT INTO #var SELECT row_number() over (ORDER BY employeeName), employeeName, cast(getdate() AS varchar(12))+employeeName FROM Table1
DECLARE #query varchar(500)
DECLARE #rowkey varchar(60), #i int, #max int
SET #i = 1
SET #max = (SELECT count(*) FROM #var)
SET #query = ''
WHILE #i <= #max
BEGIN
SET #rowkey = (SELECT rowkey FROM #var WHERE rownum = #i)
SET #query = 'select employeeName as "'+(SELECT ALIAS FROM #var WHERE rowkey = #rowkey)+'" from Table1 where employeeName = '''+#rowkey+''';'
exec(#query)
SET #i = #i + 1
END;
If you're only expecting a single value, you could use a table variable. However, if multiple rows are created it effectively becomes a temporary table. If you think that's likely, declare as a temporary table.

call sql function in stored procedure with different userId each time

I have a sql function and using sql server 2005.
dbo.util (#dailyDate,#userId)
Now I want to call this function for each #userId for a particular Date.So I am writing a Stored Procedure.
Create PROCEDURE [dbo].[DailyAttendenceTemp]
#dailyDate nvarchar(10)
WITH EXEC AS CALLER
AS
Select * FROM dbo.util (#dailyDate,#userId) //I think error is here.
WHERE #userId in (SELECT UserId From TTransactionLog1)
GO
but when I execute the procedure it give the error that-
SQL Server Database Error: Must declare the scalar variable "#userId".
So please tell me how to correct the procedure so that I give only date as a parameter and it run for the same function for each #userId.
I got the answer,,now I am using While loop and it solve my problem.......
DECLARE #i int
DECLARE #userid nvarchar(10)
DECLARE #numrows int
DECLARE #tempUserId_table TABLE (
idx smallint Primary Key IDENTITY(1,1)
, userid nvarchar(10)
)
INSERT #tempUserId_table
SELECT distinct UserID FROM TUser
-- enumerate the table
SET #i = 1
SET #numrows = (SELECT COUNT(*) FROM #tempUserId_table)
IF #numrows > 0
WHILE (#i <= (SELECT MAX(idx) FROM #tempUserId_table))
BEGIN
-- get the next userId primary key
SET #userid = (SELECT userid FROM #tempUserId_table WHERE idx = #i)
Select * FROM dbo.util (#dailyDate,#userid)
-- increment counter for next userId
SET #i = #i + 1
END

How to retrieve N random records from stored procedure?

How can I retrieve N random records from a set of X records we have in total. For example, if we have a table with 2000 links to different pages on our website how do we retrieve 10 random records?
SELECT TOP 10 *
FROM tableName
ORDER BY NEWID()
NEWID
Try using dynamics SQL like this. Note that this needs more work since some edge cases are not covered such as COUNT() returning 0 or cases where record count is greater than COUNT() and such.
CREATE PROCEDURE dbo.RandomNRecords
(
#recordCount int
)
as
begin
declare #counter int
declare #sqlQuery nvarchar(2000)
SET #sqlQuery = '
CREATE TABLE #TempTable
(
f1 varchar(50),
f2 varchar(50),
f3 int,
id int identity(1,1)
)
INSERT INTO #TempTable
SELECT f1, f2, f3 FROM Table1
SELECT *
FROM #TempTable
WHERE id in ('
SELECT #recordCount = COUNT(*) From Table1
SET #counter = 0
WHILE #counter < #recordCount
BEGIN
SET #counter = #counter + 1
SET #sqlQuery = #sqlQuery + CONVERT(varchar,Round((#recordCount * Rand()), 0)) + ','
END;
SET #sqlQuery = SUBSTRING(#sqlQuery, 1, LEN(sqlQuery) - 1) --remove last comma
SET #sqlQuery = #sqlQuery + ')'
EXEC sp_executesql #sqlQuery
END
declare #numberOfRecordsToGet int = 5
select top (#numberOfRecordsToGet) * from name_of_your_tbl order by newid()
use this in store procedure
declare #N varchar(10)
set #N='10'
exec(' SELECT TOP '+#N+' * FROM tableName ORDER BY NEWID()')

Issues with Trigger on insert (t-sql)

Say I have a self relation table as following :
ID - Name - ParentID
Now everytime that users insert sth in this table I would like to check if the Name inserted is already in the
rows where ParentID equals to the inserted one , if true then rollback the transaction.
But the problem is when I check the rows with the parentID from the inserted table the inserted row is already in the main table too. So, the trigger always rolls back the transaction.
Here is my trigger :
ALTER TRIGGER TG_Check_Existance_In_myTbl
ON myTbl FOR INSERT,UPDATE AS
DEClARE #result BIT
DECLARE #numberOfRows INT
DECLARE #counter INT
DECLARE #names nVARCHAR (30)
DECLARE #name NVARCHAR (30)
SET #result = 0
SET #numberOfRows = (SELECT COUNT (Name)
FROM myTbl
WHERE ParentID IN
(
SELECT ParentID
FROM inserted
)
)
SET #counter = 1;
SELECT #name = Name
FROM inserted
WHILE (#counter <= #numberOfRows)
BEGIN
WITH Q
AS
(
SELECT ROW_NUMBER()
OVER (ORDER BY Name) 'Row', Name
FROM myTbl WHERE ParentID IN
(
SELECT ParentID
FROM inserted
)
)
SELECT #names = Name
FROM Q
WHERE Row = #counter
IF #name = #names
SET #result=1;
SET #counter = #counter + 1
END
IF #result = 1
ROLLBACK TRAN
Unless I am missing something you are making this way too hard.
Why don't you use a unique constraint on the two columns?
table_constraint (Transact-SQL)