Skip to content

Instantly share code, notes, and snippets.

@gitfvb
Created July 18, 2022 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitfvb/dcb5fcd89b5d97f24eb031ba270c10d1 to your computer and use it in GitHub Desktop.
Save gitfvb/dcb5fcd89b5d97f24eb031ba270c10d1 to your computer and use it in GitHub Desktop.
Example

Install python support on your Microsoft SQLServer and then you can fire up synchronous events like in these examples to external services like a webhooks service. Be aware that these calls are synchronous and should process pretty fast.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER TRIGGER [dbo].[new_login] on [dbo].[Logins] AFTER INSERT as
--declare @UserName varchar(50);
begin
DECLARE @jsonObj NVARCHAR(MAX) =
(
SELECT a.[LoginID] AS id, 'logins' AS object, 'login' AS event, JSON_QUERY((
SELECT TOP 1 l.[LoginID], l.[UserName], l.[UserID], l.[ValidUserName], l.[ValidPassword], l.[LoginDateTime], l.[SystemName], l.[LogoutDateTime], l.[ClientType], u.EmailName, u.FirstName, u.LastName, u.FirstAccessDate, u.LastAccessDate
FROM INSERTED l
inner join dbo.[Users] u on l.UserID = u.UserID
FOR json path, WITHOUT_ARRAY_WRAPPER
)) AS attributes
FROM (
SELECT TOP 1 *
FROM INSERTED
) a
FOR json auto, root('hook')
)
EXEC [dbo].[EventToWebhooks]
@message_txt = @jsonObj;
End
GO
ALTER TABLE [dbo].[Logins] ENABLE TRIGGER [new_login]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[EventToWebhooks] @message_txt NVARCHAR(MAX) with execute as caller
AS
BEGIN
EXEC sp_execute_external_script @language =N'Python',
@script=N'
import json
import urllib3
urllib3.disable_warnings()
http = http = urllib3.PoolManager()
def post_to_webhooks(message):
webhooks_url = "https://webhooks.example.com/hooks/test"
#print(message)
encoded_data = message.encode(''utf-8'')
response = http.request("POST", webhooks_url, body=encoded_data, headers={''Content-Type'': ''application/json'', ''Authorization'': ''Token xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx''})
#print(str(response.status) + str(response.data))
post_to_webhooks(message_txt_in)
',
@params = N'@message_txt_in nvarchar(max)',
@message_txt_in = @message_txt
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment