How to convert YES/NO to BIT automatically in SQL Server? - sql-server

I want to override system defined conversion in SQL Server. is that possible.
Problem Statement
I have a large csv file to upload data in database. There is a column with BIT type contains True/False, Yes/No, 1/0
When I used bulk insertion True/False and '1/0' will be consider as right value but Yes/No (as expected) will throw an conversion error.
Is there any way to convert Yes/No without any looping or one by one value?
Edit
Custom data type PanelMemberType
CREATE TYPE [dbo].[PanelMemberType] AS TABLE(
[Email] [nvarchar](255) NOT NULL,
[LocationName] [nvarchar](255) NOT NULL,
[OptInPermission] [nvarchar](255) NOT NULL
)
GO
Stored procedure code:
ALTER PROCEDURE [dbo].[PanelMemberBulkUpdate]
#tblPanelMember PanelMemberType READONLY,
#PanelID int,
#UserID nvarchar(128)
AS
BEGIN
SET NOCOUNT ON;
MERGE INTO PanelMember p1
USING #tblPanelMember p2 ON p1.Email= p2.Email
WHEN MATCHED THEN
UPDATE SET
p1.PanelID = #PanelID,
p1.LocationID = (SELECT TOP(1) [LocationID]
FROM [dbo].[Location]
WHERE [LocationName] = p2.LocationName),
p1.Email = p2.Email,
p1.OptInPermission = CONVERT(BIT, p2.OptInPermission),
p1.DateAdded = p1.DateAdded,
p1.DateLastUpdated = (SELECT GETDATE()),
p1.LastUpdateUserID = #UserID
WHEN NOT MATCHED THEN
INSERT (PanelID, LocationID, Email, OptInPermission, DateAdded)
VALUES (#PanelID, (SELECT TOP(1) [LocationID]
FROM [dbo].[Location]
WHERE [LocationName] = p2.LocationName),
p2.Email, CONVERT(BIT, p2.OptInPermission),
(SELECT GETDATE()));
END

Just apply a bit more logic rather than trying to blindly convert to bit:
p1.OptInPermission = convert( bit,
CASE p2.OptInPermission
WHEN 'Yes' THEN 1
WHEN 'No' THEN 0
ELSE p2.OptInPermission END)
(Or, to avoid having to duplicate this logic in both branches of the MERGE, do it in the source:
USING (select Email,LocationName,convert( bit,
CASE p2.OptInPermission
WHEN 'Yes' THEN 1
WHEN 'No' THEN 0
ELSE p2.OptInPermission END as OptInPermission from #tblPanelMember) p2
)

Inserts records from CSV file into staging table first.
Then run the actual insert into your table and your select statement should look like this:
INSERT INTO ActualTable(column1, column2, column3)
SELECT column1
, column2
, CAST(CASE column3
WHEN 'Yes' THEN 1
WHEN 'No' THEN 0
ELSE column3
END AS BIT) AS YourBitColumn
FROM StagingTable;
Based on your approach, this should be working:
ALTER PROCEDURE [dbo].[PanelMemberBulkUpdate]
(
#tblPanelMember PanelMemberType READONLY
, #PanelID INT
, #UserID NVARCHAR(128)
)
AS
BEGIN TRY
SET NOCOUNT ON;
MERGE INTO PanelMember p1
USING #tblPanelMember p2
ON p1.Email = p2.Email
WHEN MATCHED THEN
UPDATE
SET p1.PanelID = #PanelID
, p1.LocationID = (SELECT TOP (1) [LocationID] FROM [dbo].[Location] WHERE [LocationName] = p2.LocationName)
, p1.Email = p2.Email
, p1.OptInPermission = CONVERT(BIT, CASE p2.OptInPermission
WHEN 'Yes' THEN 1
WHEN 'No' THEN 0
ELSE p2.OptInPermission
END)
, p1.DateAdded = p1.DateAdded
, p1.DateLastUpdated = GETDATE()
, p1.LastUpdateUserID = #UserID
WHEN NOT MATCHED THEN
INSERT (PanelID, LocationID, Email, OptInPermission, DateAdded)
VALUES
(
#PanelID
, (SELECT TOP (1) [LocationID] FROM [dbo].[Location] WHERE [LocationName] = p2.LocationName)
, p2.Email
, CONVERT(BIT, CASE p2.OptInPermission
WHEN 'Yes' THEN 1
WHEN 'No' THEN 0
ELSE p2.OptInPermission
END)
, GETDATE()
);
END TRY
BEGIN CATCH
THROW;
END CATCH
You cannot override default function, but you can write your own one. for instance:
CREATE FUNCTION dbo.ConvertBit
(
#Input VARCHAR(5)
)
RETURNS TABLE AS RETURN
SELECT CONVERT(BIT, CASE #Input
WHEN 'True' THEN 1
WHEN 'Yes' THEN 1
WHEN '1' THEN 1
WHEN 'False' THEN 0
WHEN 'No' THEN 0
WHEN '0' THEN 0
END AS BitColumn;
And then just query it this way:
ALTER PROCEDURE [dbo].[PanelMemberBulkUpdate]
(
#tblPanelMember PanelMemberType READONLY
, #PanelID INT
, #UserID NVARCHAR(128)
)
AS
BEGIN TRY
SET NOCOUNT ON;
MERGE INTO PanelMember p1
USING (
SELECT T.Email
, T.LocationName
, B.OptInPermission
FROM #tblPanelMember AS T
CROSS APPLY dbo.ConvertBit(T.OptInPermission) AS B(OptInPermission)
) AS p2
ON p1.Email = p2.Email
WHEN MATCHED THEN
UPDATE
SET p1.PanelID = #PanelID
, p1.LocationID = (SELECT TOP (1) [LocationID] FROM [dbo].[Location] WHERE [LocationName] = p2.LocationName)
, p1.Email = p2.Email
, p1.OptInPermission = p2.OptInPermission
, p1.DateAdded = p1.DateAdded
, p1.DateLastUpdated = GETDATE()
, p1.LastUpdateUserID = #UserID
WHEN NOT MATCHED THEN
INSERT (PanelID, LocationID, Email, OptInPermission, DateAdded)
VALUES
(
#PanelID
, (SELECT TOP (1) [LocationID] FROM [dbo].[Location] WHERE [LocationName] = p2.LocationName)
, p2.Email
, p2.OptInPermission
, GETDATE()
);
END TRY
BEGIN CATCH
THROW;
END CATCH

Related

SQL Server cursor variable not working in IF condition but working with direct input

I am trying to do some actions if it satisfies the IF condition by using cursor variable. I know for a fact its supposed to be 'hi' , because instead of variable if I do a direct input, it's leading correctly as 'hi' as below
IF (SELECT COUNT(ControlNumber)
FROM #TempOut277_P
WHERE ControlNumber = 'LS2212229209771'
GROUP BY ControlNumber) = (SELECT COUNT(counterID)
FROM [counter_Out_P]
WHERE counterID = 'LS2212229209771'
GROUP BY counterID)
BEGIN
PRINT ('hi')
END
But if I use a variable instead of 'hi', it's always printing 'hello'
SET NOCOUNT ON;
DECLARE #pcn varchar(150)
DECLARE CUR_PCN_NAME CURSOR FOR
SELECT counterID
FROM [counter_Out_P]
WHERE Reconcile_process = 0
AND counterID IN ('LS2212229209771', 'LS22122692803153', 'LS2212212807553')
OPEN CUR_PCN_NAME;
FETCH NEXT FROM CUR_PCN_NAME INTO #pcn
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #pcn
PRINT ''''+#pcn+''''
IF (SELECT COUNT(ControlNumber)
FROM #TempOut277_P
WHERE ControlNumber = #pcn
GROUP BY ControlNumber) > (SELECT COUNT(counterID)
FROM [counter_Out_P]
WHERE counterID = #pcn
GROUP BY counterID)
BEGIN
PRINT ('hello')
END
ELSE
IF (SELECT COUNT(ControlNumber)
FROM #TempOut277_P
WHERE ControlNumber = #pcn
GROUP BY ControlNumber) < (SELECT COUNT(counterID)
FROM [counter_Out_P]
WHERE counterID = #pcn
GROUP BY counterID)
BEGIN
PRINT ('hey')
END
ELSE IF (SELECT COUNT(ControlNumber)
FROM #TempOut277_P
WHERE ControlNumber = #pcn
GROUP BY ControlNumber) = (SELECT COUNT(counterID)
FROM [counter_Out_P]
WHERE counterID = #pcn
GROUP BY counterID)
BEGIN
PRINT ('hi')
END
ELSE
PRINT ('hola')
FETCH NEXT FROM CUR_PCN_NAME INTO #pcn;
END;
CLOSE CUR_PCN_NAME;
DEALLOCATE CUR_PCN_NAME;
PS: I have also tried the EXEC SQL way, but same case.
your solution seems to be driven by a procedural approach.
A more relational approach (this is where SQL shines) could be for example another temporary table in which you store all counts and the comparison of counter values. So far no cursor is necessary.
DROP TABLE IF EXISTS #newTemp;
CREATE TABLE #newTemp(
tempCounterCount [int] NOT NULL,
tempCounterId [int] NOT NULL,
CountComparison [varchar](50) NULL,
permanentCounterCount [int] NOT NULL,
permanentCounterId [int] NOT NULL
)
WITH myCTE
AS (
SELECT
COUNT(counter_id) AS CounterCount,
MAX(counter_id) AS CounterId
FROM #test_counter
GROUP BY counter_id
)
INSERT INTO #newTemp
SELECT myCTE.CounterCount AS tempCounterCount
, myCTE.CounterId AS tempCounterId
,CASE
WHEN myCTE.CounterCount = p.CounterCount THEN 'EQUAL'
ELSE 'NOT EQUAL'
END
AS CountComparison
, p.CounterCount AS permanentCounterCount
, p.CounterId AS permanentCounterId
FROM myCTE
INNER JOIN (SELECT
COUNT(counter_id) AS CounterCount,
MAX(counter_id) AS CounterId
FROM [PM].[dbo].[test_counter]
GROUP BY counter_id) AS p
ON p.CounterId = myCTE.CounterId;
-- #test_counter <- should mimic your #TempOut277_P
-- test_counter <- should mimic your counter_Out_P
-- MAX(counter_id) AS CounterId <- is just a helper function for including counter_id in the result set, there are more ways to do this
I admit my suggestion is very simplistic, but the basic idea is transferable to your scenario.
If you still need a cursor for doing procedural stuff you can iterate through the temporary table and evaluate the comparison result or whatever you want.

SQL Server cursor - cannot assign variable properly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I use SQL Server 2016. I need to move users from a legacy system to a new one. But before bringing all users from the legacy system, I need to check if they do not already exist in our new system. Such a determination is done based on comparison of users' email addresses in each of the system.
So if a user does not exist in the new system, I need to insert such a record into the new system from the legacy one. But if user does exist, I need to update some columns in the new system with data from the legacy one.
To accomplish it I'm using a cursor with SCOPE_IDENTITY().
Also I need to log newly inserted and existing updated records in each cursor iteration. The problem is that my code does not differentiate new and existing records hence it inserts all user id in the Log table twice. One time in case the userID (#ContactID) IS NULL (not existing in the new system) and another when userID (#ContactID) IS NOT NULL - existing in the new system.
In my sample below I have 1 records that does not exists in the new system and 3 do match already. So in the IF (#CoantactID IS NULL) I meant to insert only that newly inserted into the MyDB.dbo.Contact table record and in the IF (#CoantactID IS NOT NULL) insert into the Log table only the tree records matched (existing) in the new system.
But the problem is that it inserts all four ContactIDs into the log table even in the this IF (#ContactID IS NULL) amd then again for in IF (#ContactID IS NOT NULL)
;USE [MyDB];
GO
-- exec dbo.sp_UserMigration_Users_Copy
DROP PROCEDURE IF EXISTS dbo.sp_UserMigration_Users_Copy
GO
;USE [MyDB];
GO
CREATE PROCEDURE dbo.sp_UserMigration_Users_Copy
#UserID UNIQUEIDENTIFIER = NULL
--,#ContactID INT
AS
DECLARE #Email nvarchar(100),
#ContactID INT;
-- #UserID UNIQUEIDENTIFIER,
DECLARE #SysID INT
SET #SysId = 17511; -- system contactID
---- creating log table
--CREATE TABLE #T
--(
-- UserID UNIQUEIDENTIFIER NOT NULL,
-- Email NVARCHAR(50) NOT NULL
--);
SELECT * INTO #T
FROM MyDB.dbo.User
WHERE UserID IN (
'0604C514',
'C1FDAF34',
'23BABE2D',
'EBA21D10'
);
IF NOT EXISTS (select * from MyDB.sys.tables where name = N'UserIDContactIDMigrationLog')
CREATE TABLE MyDB.dbo.UserIDContactIDMigrationLog
(
UserID UNIQUEIDENTIFIER /* CONSTRAINT [PK_UserIDContactIDMigrationLog_UserID] PRIMARY KEY */ NOT NULL, -- somehow inserts duplicate UserIDs
ContactId INT /*UNIQUE CONSTRAINT [UNIQUE_ContactId] */ NOT NULL,
CreatedDt DATETIME2 NULL,
UpdatedDt DATETIME2 NULL,
UpdatedFlag BIT /*CONSTRAINT [DF_MigratedFlag] DEFAULT(0) */ NULL
);
-- -----------------------------------------------------
-- Cursor: For all contacts to be migrated
-- -----------------------------------------------------
IF (SELECT CURSOR_STATUS('global','user_cursor')) >= -1
BEGIN
IF (SELECT CURSOR_STATUS('global','user_cursor')) > -1
BEGIN
CLOSE user_cursor
END
DEALLOCATE user_cursor
END
DECLARE user_cursor CURSOR
FOR
SELECT a.UserID, LTRIM(RTRIM(a.Email)) AS Email
FROM #T a WITH (NOLOCK)
--WHERE a.UserID = #UserID
-- begin cursor loop
OPEN user_cursor
FETCH NEXT FROM user_cursor INTO #UserID, #Email
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #ContactID = (
SELECT c.ContactId
FROM MyDB.dbo.Contact c
LEFT OUTER JOIN MyDB.dbo.Login l ON c.ContactId = l.ContactId
WHERE (LTRIM(RTRIM(c.ContactEmailTx)) = #Email
OR LTRIM(RTRIM(l.ContactLoginNameTx)) = #Email
--OR l.ContactLoginNameTx LIKE #Email+'%' -- this concept does not work in case of leading space at the ContactLoginNameTx so need to use the code below
OR SUBSTRING(LTRIM(RTRIM(l.ContactLoginNameTx)), -1, CHARINDEX('.INACTIVE.', l.ContactLoginNameTx)) = #Email)
AND (c.ContactEmailTx != '' OR c.ContactEmailTx IS NOT NULL OR l.ContactLoginNameTx != '' OR l.ContactLoginNameTx IS NOT NULL)
)
-- check if a contact is new
IF (#ContactID IS NULL)
BEGIN
-- -----------------------------------------------------
-- MyDB.dbo.Contact
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[Contact]
(
[ContactFirstNameTx],
[ContactLastNameTx],
[ContactEmailTx],
[ContactTitleTx],
[ContactCreateDt],
[ContactCreateByID],
[ContactCreateLoginTypeID]
)
SELECT
[FirstName],
[LastName],
[Email],
[Title],
--[AccountId],
[UserCreatedDate],
#SysId AS [ContactCreateByID], -- as as flag for import [ContactCreateLoginTypeID]
-10 AS [ContactCreateLoginTypeID]
FROM #T o WITH (NOLOCK)
WHERE UserID = #UserID
SET #ContactID = SCOPE_IDENTITY()
END
-- select * from [MyDB].[dbo].[Contact] where contactid in ( 1051364, 466440, 560466, 618576)
-- -----------------------------------------------------
--MyDB.dbo.Login
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[Login]
(
ContactID,
[ContactLoginNameTx], -- V.C. this is email. the field is has a unique constraint
[ContactLoginActiveIn],
[ContactLoginCreateDt],
[ContactLoginCreateByID],
[ContactLoginCreateLoginTypeID],
[ContactLoginPasswordLastChangeDt],
[ContactLoginLastLoginDt],
[ContactLoginPasswordExclusionIn] -- this is not nullable and BIT
)
SELECT
#ContactID AS ContactID,
[Email],
CASE WHEN [UserStatusID] IN (1, 3) THEN 1 ELSE 0 END AS [ContactLoginActiveIn], -- v.c. in Onvia 1 is Active, 2 - Inactive, 3 - Invited, 4 - Inactive By System, 5 - Pending Registration
[UserCreatedDate],
#SysId AS ContactLoginCreateByID, -- as as flag for Onvia import[ContactCreateLoginTypeID]
-10 AS [ContactLoginCreateLoginTypeID],
[UserLastPasswordChangedDate],
[UserLastLoginDate],
0 as ContactLoginPasswordExclusionIn -- this is not nullable and BIT
FROM #T o WITH (NOLOCK)
WHERE UserID = #UserID
AND NOT EXISTS (select * from MyDB.dbo.Login z where z.ContactID = #ContactID)
-- -----------------------------------------------------
-- Activate any inactive users
-- -----------------------------------------------------
IF EXISTS (select * from MyDB.dbo.Login where ContactLoginActiveIn = 0 and ContactID = #ContactID)
AND NOT EXISTS (select * from MyDB.dbo.Login where ContactLoginActiveIn = 1 and ContactID = #ContactID)
BEGIN
UPDATE [MyDB].[dbo].[Login]
SET ContactLoginNameTx = #Email,
ContactLoginActiveIn = (select case when [UserStatusID] IN (1, 3) then 1 else 0 end
from #T o where o.UserID = #UserID)
WHERE ContactID = #ContactID
END
-- -----------------------------------------------------
--MyDB.dbo.ContactPhoneNumber
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[PhoneNumber]
(
ContactID,
PhoneNumberTypeID,
ContactPhoneNumberValueTx
)
SELECT
#ContactID AS ContactID,
1 AS PhoneNumberTypeID,
ISNULL([PhoneNumber1],'') AS ContactPhoneNumberValueTx
FROM #T o WITH (NOLOCK)
WHERE o.UserID = #UserID
AND NOT EXISTS (select * from [MyDB].[dbo].[PhoneNumber] z where z.ContactID = #ContactID);
-- -----------------------------------------------------
--MyDB.dbo.ContactOrg
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[Org]
(
ContactID,
OrgID
)
SELECT
#ContactID AS ContactID,
b.OrgID AS OrgID
FROM #T o WITH (NOLOCK)
INNER JOIN ImportQueue.dbo.OnviaAccountIDOrgIDMigrationLog b WITH (NOLOCK) ON o.AccountId = b.OnviaAccountID
WHERE o.UserID = #UserID
AND NOT EXISTS (select * from [MyDB].[dbo].[Org] z where z.ContactID = #ContactID);
-- -----------------------------------------------------
---- MyDB.dbo.UserIDContactIDMigrationLog
---- log output for new users
-- -----------------------------------------------------
INSERT INTO MyDB.dbo.UserIDContactIDMigrationLog
(
UserID,
ContactId,
CreatedDt,
UpdatedFlag
)
VALUES
(
#UserID,
#ContactID,
GETDATE(),
0
)
-- -----------------------------------------------------
-- EXISTING MATCHED USERS
-- -----------------------------------------------------
-- check if a contact is existing
IF (#ContactID IS NOT NULL)
BEGIN
-- -----------------------------------------------------
-- MyDB.dbo.Contact
-- -----------------------------------------------------
UPDATE MyDB.dbo.Contact
SET ContactFirstNameTx =
CASE
WHEN ContactFirstNameTx NOT IN ('', NULL) THEN c.FirstName
ELSE ContactFirstNameTx
END,
ContactLastNameTx =
CASE
WHEN ContactLastNameTx IN ('', NULL) THEN c.LastName
ELSE ContactLastNameTx
END,
ContactEmailTx =
CASE
WHEN ContactEmailTx IN ('', NULL) THEN c.Email
ELSE ContactEmailTx
END,
ContactTitleTx =
CASE
WHEN ContactTitleTx IN ('', NULL) THEN c.Title
ELSE ContactTitleTx
END,
[ContactCreateDt] =
CASE
WHEN ContactCreateDt IN ('', NULL) THEN c.UserCreatedDate
ELSE ContactCreateDt
END,
[ContactModifyByID] = #SysId,
[ContactModifyLoginTypeID] = - 10
FROM #T c
WHERE UserID = #UserID
AND ContactID = #ContactID;
-- -----------------------------------------------------
---- MyDB.dbo.UserIDContactIDMigrationLog
---- log output for existing matched users
-- -----------------------------------------------------
INSERT INTO MyDB.dbo.UserIDContactIDMigrationLog
(
UserID,
ContactId,
UpdatedDt,
UpdatedFlag
)
VALUES
(
#UserID,
#ContactID,
GETDATE(),
1
);
FETCH NEXT FROM user_cursor INTO #UserID, #Email
-- end cursor loop
END
END
CLOSE user_cursor
DEALLOCATE user_cursor
GO
Instead of Cursors try the below code.
- exec dbo.sp_UserMigration_Users_Copy
DROP PROCEDURE IF EXISTS dbo.sp_UserMigration_Users_Copy
GO
;USE [MyDB];
GO
CREATE PROCEDURE dbo.sp_UserMigration_Users_Copy
#UserID UNIQUEIDENTIFIER = NULL
--,#ContactID INT
AS
DECLARE #Email nvarchar(100),
#ContactID INT;
DECLARE #SysID INT
SET #SysId = 17511;
CREATE TABLE #T
(
ID INT IDENTITY(1,1) NOT NULL,
UserID NVARCHAR(50)NOT NULL,
Email NVARCHAR(50) NOT NULL
);
INSERT INTO #T
SELECT *
FROM MyDB.dbo.User
WHERE UserID IN (
'0604C514',
'C1FDAF34',
'23BABE2D',
'EBA21D10'
);
IF NOT EXISTS (select * from MyDB.sys.tables where name = N'UserIDContactIDMigrationLog')
CREATE TABLE MyDB.dbo.UserIDContactIDMigrationLog
(
UserID UNIQUEIDENTIFIER /* CONSTRAINT [PK_UserIDContactIDMigrationLog_UserID] PRIMARY KEY */ NOT NULL, -- somehow inserts duplicate UserIDs
ContactId INT /*UNIQUE CONSTRAINT [UNIQUE_ContactId] */ NOT NULL,
CreatedDt DATETIME2 NULL,
UpdatedDt DATETIME2 NULL,
UpdatedFlag BIT /*CONSTRAINT [DF_MigratedFlag] DEFAULT(0) */ NULL
);
DECLARE #COUNT INT
DECLARE #I INT = 1
DECLARE #UserID NVARCHAR(50) ;
DECLARE #Email NVARCHAR(50)
SELECT #COUNT = COUNT(*) FROM #T
WHILE(#I <= #COUNT)
BEGIN
SELECT #UserID = UserID, #Email= LTRIM(RTRIM(Email)) FROM #T WHERE ID = #I
SELECT #ContactID = (
SELECT c.ContactId
FROM MyDB.dbo.Contact c
LEFT OUTER JOIN MyDB.dbo.Login l ON c.ContactId = l.ContactId
WHERE (LTRIM(RTRIM(c.ContactEmailTx)) = #Email
OR LTRIM(RTRIM(l.ContactLoginNameTx)) = #Email
--OR l.ContactLoginNameTx LIKE #Email+'%' -- this concept does not work in case of leading space at the ContactLoginNameTx so need to use the code below
OR SUBSTRING(LTRIM(RTRIM(l.ContactLoginNameTx)), -1, CHARINDEX('.INACTIVE.', l.ContactLoginNameTx)) = #Email)
AND (c.ContactEmailTx != '' OR c.ContactEmailTx IS NOT NULL OR l.ContactLoginNameTx != '' OR l.ContactLoginNameTx IS NOT NULL)
)
-- check if a contact is new
IF (#ContactID IS NULL)
BEGIN
-- -----------------------------------------------------
-- MyDB.dbo.Contact
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[Contact]
(
[ContactFirstNameTx],
[ContactLastNameTx],
[ContactEmailTx],
[ContactTitleTx],
[ContactCreateDt],
[ContactCreateByID],
[ContactCreateLoginTypeID]
)
SELECT
[FirstName],
[LastName],
[Email],
[Title],
--[AccountId],
[UserCreatedDate],
#SysId AS [ContactCreateByID], -- as as flag for Onvia import[ContactCreateLoginTypeID]
-10 AS [ContactCreateLoginTypeID]
FROM #T o WITH (NOLOCK)
WHERE UserID = #UserID
SET #ContactID = SCOPE_IDENTITY()
END
-- select * from [MyDB].[dbo].[Contact] where contactid in ( 1051364, 466440, 560466, 618576)
-- -----------------------------------------------------
--MyDB.dbo.Login
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[Login]
(
ContactID,
[ContactLoginNameTx], -- V.C. this is email. the field is has a unique constraint
[ContactLoginActiveIn],
[ContactLoginCreateDt],
[ContactLoginCreateByID],
[ContactLoginCreateLoginTypeID],
[ContactLoginPasswordLastChangeDt],
[ContactLoginLastLoginDt],
[ContactLoginPasswordExclusionIn] -- this is not nullable and BIT
)
SELECT
#ContactID AS ContactID,
[Email],
CASE WHEN [UserStatusID] IN (1, 3) THEN 1 ELSE 0 END AS [ContactLoginActiveIn], -- v.c. in Onvia 1 is Active, 2 - Inactive, 3 - Invited, 4 - Inactive By System, 5 - Pending Registration
[UserCreatedDate],
#SysId AS ContactLoginCreateByID, -- as as flag for Onvia import[ContactCreateLoginTypeID]
-10 AS [ContactLoginCreateLoginTypeID],
[UserLastPasswordChangedDate],
[UserLastLoginDate],
0 as ContactLoginPasswordExclusionIn -- this is not nullable and BIT
FROM #T o WITH (NOLOCK)
WHERE UserID = #UserID
AND NOT EXISTS (select * from MyDB.dbo.Login z where z.ContactID = #ContactID)
-- -----------------------------------------------------
-- Activate any inactive users
-- -----------------------------------------------------
IF EXISTS (select * from MyDB.dbo.Login where ContactLoginActiveIn = 0 and ContactID = #ContactID)
AND NOT EXISTS (select * from MyDB.dbo.Login where ContactLoginActiveIn = 1 and ContactID = #ContactID)
BEGIN
UPDATE [MyDB].[dbo].[Login]
SET ContactLoginNameTx = #Email,
ContactLoginActiveIn = (select case when [UserStatusID] IN (1, 3) then 1 else 0 end
from #T o where o.UserID = #UserID)
WHERE ContactID = #ContactID
END
-- -----------------------------------------------------
--MyDB.dbo.ContactPhoneNumber
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[PhoneNumber]
(
ContactID,
PhoneNumberTypeID,
ContactPhoneNumberValueTx
)
SELECT
#ContactID AS ContactID,
1 AS PhoneNumberTypeID,
ISNULL([PhoneNumber1],'') AS ContactPhoneNumberValueTx
FROM #T o WITH (NOLOCK)
WHERE o.UserID = #UserID
AND NOT EXISTS (select * from [MyDB].[dbo].[PhoneNumber] z where z.ContactID = #ContactID);
-- -----------------------------------------------------
--MyDB.dbo.ContactOrg
-- -----------------------------------------------------
INSERT INTO [MyDB].[dbo].[Org]
(
ContactID,
OrgID
)
SELECT
#ContactID AS ContactID,
b.OrgID AS OrgID
FROM #T o WITH (NOLOCK)
INNER JOIN ImportQueue.dbo.OnviaAccountIDOrgIDMigrationLog b WITH (NOLOCK) ON o.AccountId = b.OnviaAccountID
WHERE o.UserID = #UserID
AND NOT EXISTS (select * from [MyDB].[dbo].[Org] z where z.ContactID = #ContactID);
-- -----------------------------------------------------
---- MyDB.dbo.UserIDContactIDMigrationLog
---- log output for new users
-- -----------------------------------------------------
INSERT INTO MyDB.dbo.UserIDContactIDMigrationLog
(
UserID,
ContactId,
CreatedDt,
UpdatedFlag
)
VALUES
(
#UserID,
#ContactID,
GETDATE(),
0
)
-- -----------------------------------------------------
-- EXISTING MATCHED USERS
-- -----------------------------------------------------
-- check if a contact is existing
IF (#ContactID IS NOT NULL)
BEGIN
-- -----------------------------------------------------
-- MyDB.dbo.Contact
-- -----------------------------------------------------
UPDATE MyDB.dbo.Contact
SET ContactFirstNameTx =
CASE
WHEN ContactFirstNameTx NOT IN ('', NULL) THEN c.FirstName
ELSE ContactFirstNameTx
END,
ContactLastNameTx =
CASE
WHEN ContactLastNameTx IN ('', NULL) THEN c.LastName
ELSE ContactLastNameTx
END,
ContactEmailTx =
CASE
WHEN ContactEmailTx IN ('', NULL) THEN c.Email
ELSE ContactEmailTx
END,
ContactTitleTx =
CASE
WHEN ContactTitleTx IN ('', NULL) THEN c.Title
ELSE ContactTitleTx
END,
[ContactCreateDt] =
CASE
WHEN ContactCreateDt IN ('', NULL) THEN c.UserCreatedDate
ELSE ContactCreateDt
END,
[ContactModifyByID] = #SysId,
[ContactModifyLoginTypeID] = - 10
FROM #T c
WHERE UserID = #UserID
AND ContactID = #ContactID;
-- -----------------------------------------------------
---- MyDB.dbo.UserIDContactIDMigrationLog
---- log output for existing matched users
-- -----------------------------------------------------
INSERT INTO MyDB.dbo.UserIDContactIDMigrationLog
(
UserID,
ContactId,
UpdatedDt,
UpdatedFlag
)
VALUES
(
#UserID,
#ContactID,
GETDATE(),
1
);
END
SET #I = #I+1;
END

My stored procedure cannot show any record in application

I use this stored procedure in my application to fetch record but there is no record fetch from db using this SP.Give message that no Record found
CREATE PROCEDURE [dbo].[Proc_RptDailySummaryPTCLBillsCollection_Result]
(
#DateFrom DATETIME,
#DatTo DATETIME,
#SubOfficeID VARCHAR(200),
#GroupId INT,
#ClerkName VARCHAR(200),
#Type VARCHAR(200)
)
AS BEGIN
DECLARE #AgencyTable TABLE (
GpoId INT
, OfcId INT
, Total_Bills BIGINT
, Total_Amount BIGINT
) --Bill_Value BIGINT, Commission BIGINT,
--SET #DatTo = convert(datetime, convert(Varchar(12), #DatTo, 109) + ' 23:59:59PM')
-- Billing Summary By GPO Name
INSERT #AgencyTable (GpoId, OfcId, Total_Bills, Total_Amount) --Bill_Value, Commission,
SELECT
Bil.GroupId
, Bil.SubOfficeId
, ISNULL(COUNT(Bil.ConsumerNumber), 0) --AS Total_Bills,
-- ,ISNULL(SUM(Bil.C_Amount),0) --AS Bill_Value,
--,ISNULL(SUM(Bil.Commission),0) --AS Commission,
, ISNULL(SUM(Bil.C_Amount), 0) - ISNULL(SUM(Bil.Commission), 0) --AS Total_Amount
FROM BillTxnSO AS Bil
INNER JOIN pp_offices ofc ON Bil.GroupId = ofc.Group_Id AND Bil.SubOfficeId = ofc.OfficeCode
WHERE Bil.GroupId = #GroupId
AND TransDate BETWEEN #DateFrom AND #DatTo
GROUP BY Bil.GroupId, Bil.SubOfficeId
--select * from #AgencyTable
SELECT
ofc.OfficeName AS SubOffice
, ofc.Group_ID AS GroupID
, ISNULL(gpo.Total_Bills, 0) AS NoOfBills
, ISNULL(gpo.Total_Amount, 0) AS Amount -- isnull(gpo.Bill_Value,0)as Bill_Value , isnull(gpo.Commission,0) as Commission,
FROM #AgencyTable gpo
INNER JOIN pp_offices ofc ON ofc.Group_ID = gpo.GpoId AND gpo.OfcId = ofc.OfficeCode
ORDER BY ofc.OfficeName
END
"Give message that no record found"
Use ##ROWCOUNT
IF(##ROWCOUNT = 0)BEGIN
Select 'No record found'
return
END

Sort row on datetime in stored procedure with temp table

I am having a stored procedure which selects data from multiple tables(using joins) and returns it in a sorted order (asc or desc) based on the provided column.
For generating the sorted result based on the input, I use a Temp Table.
My problem is, when the provided column is of datetime, then the sorting is not working.
For other columns, the procedure works as expected.
This is the code I a using.
ALTER PROCEDURE [dbo].[usp_GetEULADetails]
(
#OrgKey INT
,#FilterParams FilterTypes READONLY,
/*– Sorting Parameters */
#SortColumn nvarchar(20) = 'Status' -- BranchCode
,#SortOrder nvarchar(4) = 'Asc'
/*– Pagination Parameters */
,#PageNumber int = 0
,#PageSize int = 0
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SortCol nvarchar(20),
#FirstRec int,
#LastRec int,
#TotalRows int,
#GlobalSearch nvarchar(100),
#EULAVersionNumber nvarchar(100)
DECLARE #StatusKey INT =(SELECT dbo.GetStatusKey('ACTIVE'))
DECLARE #RowCountSelected INT
SELECT
#EULAVersionNumber = LTRIM(RTRIM(Value))
FROM #FilterParams
WHERE [FieldName] = 'EULAVersions'
SELECT
#GlobalSearch = LTRIM(RTRIM(Value))
FROM #FilterParams
WHERE [IsGlobal] = 1
SET #SortCol = LTRIM(RTRIM(#SortColumn))
SET #FirstRec = (#PageNumber - 1) * #PageSize
SET #LastRec = (#PageNumber * #PageSize + 1)
CREATE TABLE #ResultTempTable (
ROWNUM int
,ORGKEY int
,EULAVersionKey int
,EULAVersionNumber varchar(25)
,EULAVersionUpdateDate datetime
,STATUSKEY tinyint
,DocumentFileName varchar(100)
,DocumentGUID varchar(100)
,DocumentTypeName varchar(50)
,DocumentDescription varchar(128)
,ContactKey int
,ContactFirstName varchar(50)
,ContactMiddleName varchar(50)
,ContactLastName varchar(50)
,StatusName varchar(25)
)
insert into #ResultTempTable (
ROWNUM
,ORGKEY
,EULAVersionKey
,EULAVersionNumber
,EULAVersionUpdateDate
,STATUSKEY
,DocumentFileName
,DocumentGUID
,DocumentTypeName
,DocumentDescription
,ContactKey
,ContactFirstName
,ContactMiddleName
,ContactLastName
,StatusName
)
(
SELECT
ROW_NUMBER() OVER (ORDER BY
CASE
WHEN (#SortCol = 'EULAVersionNumber' AND
#SortOrder = 'ASC') THEN V.EULAVersionNumber
END ASC,
CASE
WHEN (#SortCol = 'EULAVersionNumber' AND
#SortOrder = 'DESC') THEN V.EULAVersionNumber
END DESC,
CASE
WHEN (#SortCol = 'DocumentFileName' AND
#SortOrder = 'ASC') THEN V.DocumentFileName
END ASC,
CASE
WHEN (#SortCol = 'DocumentFileName' AND
#SortOrder = 'DESC') THEN V.DocumentFileName
END DESC,
CASE
WHEN (#SortCol = 'EULAVersionUpdateDate' AND
#SortOrder = 'ASC') THEN convert(date, V.EULAVersionUpdateDate,103)
END ASC,
CASE
WHEN (#SortCol = 'EULAVersionUpdateDate' AND
#SortOrder = 'DESC') THEN convert(date, V.EULAVersionUpdateDate,103)
END DESC,
CASE
WHEN (#SortCol = 'ContactFirstName' AND
#SortOrder = 'ASC') THEN V.ContactFirstName
END ASC,
CASE
WHEN (#SortCol = 'ContactFirstName' AND
#SortOrder = 'DESC') THEN V.ContactFirstName
END DESC,
CASE
WHEN (#SortCol = 'StatusKey' AND
#SortOrder = 'ASC') THEN V.StatusKey
END ASC,
CASE
WHEN (#SortCol = 'StatusKey' AND
#SortOrder = 'DESC') THEN V.StatusKey
END DESC
) AS ROWNUM
,[ORGKEY]
,[EULAVersionKey]
,[EULAVersionNumber]
,[EULAVersionUpdateDate]
,[STATUSKEY]
,[DocumentFileName]
,[DocumentGUID]
,[DocumentTypeName]
,[DocumentDescription]
,[ContactKey]
,[ContactFirstName]
,[ContactMiddleName]
,[ContactLastName]
,[StatusName]
FROM (
SELECT
EUV.[ORGKEY]
,EUV.[EULAVersionKey]
,EUV.[EULAVersionNumber]
,EUV.[EULAVersionUpdateDate]
,EUV.[STATUSKEY]
,DOC.[DocumentFileName]
,DOC.[DocumentGUID]
,DOC.[DocumentDescription]
,DOCTYP.[DocumentTypeName]
,CN.[ContactKey]
,CN.[ContactFirstName]
,CN.[ContactMiddleName]
,CN.[ContactLastName]
,ST.[StatusName]
FROM [dbo].[EULAVersions] EUV
JOIN [dbo].[Documents] DOC
ON DOC.[DocumentKey] =EUV.[DocumentKey]
JOIN[dbo].[DocumentTypes] DOCTYP
ON DOCTYP.[DocumentTypeKey]=EUV.[DocumentTypeKey]
JOIN [dbo].[UserContacts] UC
ON UC.[UserKey]=EUv.[EULAVersionUpdatedBy]
JOIN [dbo].[Contacts] CN
ON CN.[ContactKey]=UC.[ContactKey]
JOIN [dbo].[StatusTypes] ST
ON ST.[StatusKey]=EUV.[StatusKey]
WHERE
EUV.[ORGKEY]=#OrgKey --AND EUV.[StatusKey]=#StatusKey
AND EUV.[EULAVersionNumber] LIKE '%' + ISNULL(#EULAVersionNumber, EULAVersionNumber) + '%'
AND EUV.[EULAVersionNumber] LIKE '%' + ISNULL(#GlobalSearch, EULAVersionNumber) + '%') AS V
)
IF (#PageNumber <> 0)
BEGIN
SELECT
#TotalRows = COUNT(1)
FROM #ResultTempTable AS CPC
WHERE ROWNUM BETWEEN #FirstRec AND CASE
WHEN #PageNumber = 0 THEN #TotalRows
ELSE #LastRec
END
SELECT
[ORGKEY]
,[EULAVersionKey]
,[EULAVersionNumber]
,[EULAVersionUpdateDate]
,[STATUSKEY]
,[DocumentFileName]
,[DocumentGUID]
,[DocumentDescription]
,[DocumentTypeName]
,[ContactFirstName]
,[ContactMiddleName]
,[ContactLastName]
,[StatusName]
FROM #ResultTempTable AS CPC
WHERE ROWNUM BETWEEN #FirstRec AND CASE
WHEN #PageNumber = 0 THEN #TotalRows
ELSE #LastRec
END
ORDER BY ROWNUM ASC
END
ELSE
BEGIN
SELECT
#TotalRows = COUNT(1)
FROM #ResultTempTable AS CPC
SELECT
[ORGKEY]
,[EULAVersionKey]
,[EULAVersionNumber]
,[EULAVersionUpdateDate]
,[STATUSKEY]
,[DocumentFileName]
,[DocumentGUID]
,[DocumentDescription]
,[DocumentTypeName]
,[ContactFirstName]
,[ContactMiddleName]
,[ContactLastName]
,[StatusName]
FROM #ResultTempTable AS CPC
ORDER BY ROWNUM ASC
END
SELECT #TotalRows AS TotalCount
IF OBJECT_ID('tempdb..#ResultTempTable') IS NOT NULL
DROP TABLE #ResultTempTable
END
--FilterTypes Details
CREATE TYPE [dbo].[FilterTypes] AS TABLE(
[FieldName] [varchar](100) NOT NULL,
[Value] [varchar](800) NOT NULL,
[IsGlobal] [bit] NULL DEFAULT ((0))
)
Sample Exec
declare #FilterParams AS FilterTypes;
insert into #FilterParams values('EULAVersions','',1)
exec [usp_GetEULADetails] 2,#FilterParams,'EULAVersionUpdateDate','desc',0,0
Obtained Result
Expected Result
declare #FilterParams AS FilterTypes;
insert into #FilterParams values('EULAVersions','',1)
exec [usp_GetEULADetails] 2,#FilterParams,'ContactFirstName','desc',0,0
The issue I face is how to properly sort the data when data type is of datetime ?
Thanks for the help in advance....
You are converting 'V.EULAVersionUpdateDate' to date DataType (...THEN convert(date, V.EULAVersionUpdateDate,103)) , use DATETIME Datatype to convert
THEN convert(DateTime, V.EULAVersionUpdateDate,103)

Issue in T-SQL while checking null variable

I am writing a trigger in SQL Server like this
DECLARE #N_CATComp smallint, #EXON varchar(69), #DATEDEB varchar(15), #DATEFIN varchar(15)
SELECT
#N_CATComp = N_CATCompta,
#EXON =[Exon N°],
#DATEDEB = CONVERT(varchar(15), [Date début] , 103),
#DATEDEB = CONVERT(varchar(15), [Date début] , 103)
FROM INSERTED
IF (#N_CATComp =4) AND ( ISNULL(#EXON,'')='' OR ISNULL(#DATEDEB,'') ='' OR ISNULL(#DATEFIN,'') ='')
BEGIN
RAISERROR('false',11,1)
END
MY problem is that when #exon, #datedeb,#datefin are not null and catcomp=4 the raiserror appears which it shouldn't
i tried to elpace isnull by for example len(#EXON)=0 in this case ven if the values are null then the raiserror don't appears
Here is the same thing with all those scalar variables removed.
IF EXISTS
(
SELECT *
from inserted
where N_CATCompta = 4
AND
(
ISNULL([Exon N°], '') = ''
OR
ISNULL([Date début], '') = ''
)
)
RAISERROR('false',11,1)

Resources