You could in theory check sys.dm_tran_locks
to see if there is an existing lock, and otherwise wait and loop again.
DECLARE @startLoop datetime2 = SYSUTCDATETIME();
WHILE 1=1
BEGIN
IF NOT EXISTS (SELECT 1
FROM sys.dm_tran_locks l
JOIN sys.tables t ON t.object_id = l.resource_associated_entity_id
JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE l.resource_database_id = DB_ID()
AND t.name = @tableName
AND s.name = @schemaName
)
BEGIN
EXEC sp_executesql @truncateCommand;
BREAK;
END;
IF SYSUTCDATETIME() > DATEADD(second, 10, @startLoop)
BEGIN
PRINT 'Could not acquire lock for table ' + @tableName;
BREAK;
END;
WAITFOR DELAY '00:00:02';
END;
But as noted by others, this can be unreliable as it's not guaranteed that someone won't pre-empt you in between checking and actually truncating. It also puts extra pressure on the lock manager.
If you have an identical table to this then you can use ALTER TABLE SWITCH
and the WAIT_AT_LOW_PRIORITY
option to fast-switch the table into another, then truncate that table. Note that this option does not require the above loop.
ALTER TABLE someTable SWITCH TO someTableStaging
WITH (WAIT_AT_LOW_PRIORITY (
MAX_DURATION = 1 MINUTES,
ABORT_AFTER_WAIT = SELF -- BLOCKERS is another option
) );
TRUNCATE TABLE someTableStaging;
Assuming this is related to your previous question on a partitioned table, you can do
ALTER TABLE someTable SWITCH PARTITION 10 TO someTableStaging